How to make UITableviewCell Dynamic Height and Expand iOS

Many application has dynamic contents to show from the server. Also many applications has a design to show some controls/views when the user selects the cell to expand.

So, we need to calculate the tableview cell height dynamic and assign to the UITableView Datasource and Delegates.

1. Calculate Table Cell Height

CGFloat height = 5.0f;

    // We are calculating the height based on the value..

    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@”6.0″)) {

      NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;

        height += [dynamicString boundingRectWithSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width20, 9999) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont fontWithName:@”Helvetica” size:16], NSParagraphStyleAttributeName:paragraphStyle} context:nil].size.height;

}

    else {

        height += ceilf([dynamicString sizeWithFont:[UIFont fontWithName:@”Helvetica” size:16] constrainedToSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width20, 9999) lineBreakMode:NSLineBreakByWordWrapping].height);

    }

Here is a sample view controller with Tableview integrated..

#import “ViewController.h”

#import “DemoTableViewCell.h”

@interface ViewController ()

@property (nonatomic, unsafe_unretained) IBOutlet UITableView *demoTV;

@property (nonatomic, strong) NSMutableArray *heightArray;

@property (assign) BOOL isNeedToExpand;

@end

static NSString *demoTableCellID = @”DemoTableViewCellIdentifier”;

#define IS_IPHONE5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height – ( double )568 ) < DBL_EPSILON )

#define SYSTEM_VERSION_EQUAL_TO(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)

#define SYSTEM_VERSION_GREATER_THAN(v)             ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

#define SYSTEM_VERSION_LESS_THAN(v)                ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)    ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    self.title = @”Home”;

    self.isNeedToExpand = NO;

    

}

#pragma mark- Webservice Call

– (void) fetchDataFromServer {

    

    // Storing the dynamic height in an array…

    CGFloat height = 0;

    CGFloat captionHeight = [ViewController calculateDynamicCellHeight:@”Value from server”];

    height = height + captionHeight + 10;

    [self.heightArray addObject:[NSString stringWithFormat:@”%f”,captionHeight]];

}

#pragma mark- UITableview Delegate

– (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;

}

– (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 4;

}

– (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    

    // Here you can handle the dynamic height from an heightArray values..

    

    if (self.isNeedToExpand) {

        if ((indexPath.row == 2) || (indexPath.row == 1)) {

            return 110;

        } else {

            return 50;

        }

    }

    return 50;

}

– (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    

    DemoTableViewCell *cell = (DemoTableViewCell *) [tableView dequeueReusableCellWithIdentifier:demoTableCellID forIndexPath:indexPath];

    

    if ((indexPath.row == 2) || (indexPath.row == 1)) {

        cell.hiddenLabel.hidden = NO;

    } else {

        cell.hiddenLabel.hidden = YES;

    }

    

    return cell;

}

– (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    

    // Here you have to handle the indexPath which needs to be expand based on the height..

    

    [self.demoTV beginUpdates];

    if ((indexPath.row == 2) || (indexPath.row == 1)) {

        self.isNeedToExpand = YES;

    } else {

        self.isNeedToExpand = NO;

    }

    [self.demoTV endUpdates];

}

// We are calculating the dynamic cell height based on the string…

#pragma mark- Calcualte Cell Height

+ (CGFloat) calculateDynamicCellHeight: (NSString *) dynamicString {

    

    CGFloat height = 5.0f;

    // We are calculating the height based on the value..

    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@”6.0″)) {

        

        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;

        

        height += [dynamicString boundingRectWithSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width20, 9999) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont fontWithName:@”Helvetica” size:16], NSParagraphStyleAttributeName:paragraphStyle} context:nil].size.height;

        

    }

    else {

        height += ceilf([dynamicString sizeWithFont:[UIFont fontWithName:@”Helvetica” size:16] constrainedToSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width20, 9999) lineBreakMode:NSLineBreakByWordWrapping].height);

    }

    

    return height;

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

The above source code is just for an idea about dynamic height and expanding cells. Ourself we have to manage the cell views as per our requirement.

Hope it will help someone. Happy Coding. Thanks.

How to check Internet connection in iOS apps?

Hi Coders,

Am going to explain about to manage the Internet check in Xcode projects. Apple providing the “Reachability” class to manage the Internet connection and connection status.

Here you can download the “Reachability” class files.

Follow the steps in Xcode project:

1. Import “Reachability” class files both .m and .h into the project

2. I have one Singleton class file named “MyAppManager”. There I Imported “Reachability.h” file

3. Create a  BOOL method like below,

    In .h file:

      + (BOOL) checkForInternetConnection;      

    In .m file:

  + (BOOL) checkForInternetConnection {

    Reachability *reachabilityObj = [Reachability reachabilityForInternetConnection];

    NetworkStatus status = [reachabilityObj currentReachabilityStatus];

    

    if (!status == NotReachable) {

        return YES;

    } else {

        return NO;

    }

}

4. In the ViewController class import “MyAppManager.h” file

5. Add the code like below to check the Internet connection,

 

if ([MyAppManager checkForInternetConnection]) {

NSLog(@“Internet connected”);

} else {

NSLog(@“No Internet Connection. Please check your Internet connection”);

}

6. Here we can manage the API Call or other stuffs.

Hope it will help you lot. Please share your comments and feedback. Thanks.

Happy Coding!

Yuvaraj Manickam

How to compare two NSDate values in iOS app?

Hi coders,

Now am going to post about to compare two NSDate values in iOS.

We all know well to compare two NSString values but recently I came to know about to compare two NSDate values ha ha…
Am going to share with you all about that,

NSDate *today = [NSDate date];
NSDate *compareDate = [NSDate dateWithString:@”your date”];

NSComparisonResult compareResult = [today compare : compareDate];

if (compareResult == NSOrderedAscending)
{
NSLog(@”CompareDate is in the future”);
}
else if (compareResult == NSOrderDescending)
{
NSLog(@”CompareDate is in the past”);
}
else
{
NSLog(@”Both dates are the same”);
}

 

This is the simple way to compare two Date Values. Please share your feedback on this.

Happy Coding!

Warm Regards,
Yuvaraj Manickam

CocoaPod integration in XCode

Basically we may use many third party frameworks/libraries, class files in our iOS development. The frameworks and libraries will be updated frequently with new iOS version comfortability.

Here am going to write about What is CocoaPod? And How to implement in Xcode app?

What is CocoaPod?

       CocoaPods is an open source dependency manager for Swift and Objective-C Cocoa projects. CocoaPods makes it easy to install or update new SDKs when working with Xcode.

It has over ten thousand libraries and can help you scale your projects elegantly. For more info https://cocoapods.org/.

How to install CocoaPod in Xcode project?

  1. Navigate to the project folder in Terminal: cd /projectPath
  2. Install CocoaPod in OS X: sudo gem install cocoapods
  3. It will ask for the Machine Password. Then the cocoapods will be installed.
  4. Now, we need to set up Cocoapod: pod setup
  5. Now the cocoapod setup will be downloaded the setup
  6. Now we can see the Pod setup in our Xcode project. .xcworkspace will be installed for our project. There we can see the podfile.
  7. Open the podfile and add the frameworks what we required for the project.
  8. Eg: target ‘sampleApp’ do

end

target ‘sampleApp’ do

end

target ‘sampleApp’ do

end

platform :ios, ‘7.0’

pod “AFNetworking”, “~> 2.0”

pod ‘MBProgressHUD’, ‘~> 0.9.1’

  1. Now, its time to install the framework dependencies: pod install

 

These are the simple steps to install the CocoaPod for our iOS project.

Hope it will be useful and please share your feedback on this.

Happy coding.

 

What is Extensions in Swift?

What is Extension in Swift?

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code.
Extensions are similar to the Categories in Objective- C.

Extensions in Swift can:
•    Add computed properties and computed type properties
•    Define instance methods and type methods
•    Provide new initializers
•    Define subscripts
•    Define and use new nested types
•    Make an existing type conform to a protocol
The important thing is we can’t override the existing functionality of the superclass. We
can extend the superclass with new functionalities.

We no need to import the extension class anywhere to access.

Syntax:

extension className {
// Methods Or Functionalities
}

Eg:
1. Create a new Swift File and name it as “String+Extension” it will be created with the extension “swift”.
2. Import the UIKit framework in the extension class. import UIKit
3. Create an Extension of the superclass String like below:

extension String {

}

4. Add the own methods by extending the functionality of the superclass “String”. Here I added simple methods to understand the use of Extension.

import Foundation
import UIKit

extension String {

static func stringAdding (firstString: String?, secondString: String?) -> String     {

return firstString! + secondString!
}

static func stringUppercase (inputString: String) -> String {
return inputString.uppercaseString;
}
}

5. From your ViewController you can access the Extension methods of String. It will be accessible in all classes. We no need to import

var finalString = String.stringAdding(“Abc”, secondString: “Def”)
print(“FinalString: \(finalString)”)
finalString = String.stringUppercase(finalString)
print(“Uppercase: \(finalString)”)

6. The output will be like below

FinalString: AbcDef
Uppercase: ABCDEF

Hope this post will give you simple understand on Extension in Swift. If you have any queries please share with me. Also share your feedback on this. Thanks.

What is Optional in Swift?

What is Optional? and Why Optional?

When declaring variables in Swift, they are designated as non-optional by default. In other words, we have to assign a non-nil value to the variable. Otherwise, the compiler will show the error.
If we are declaring the variable as Optional (?) we can pass the nil value to the variable.
If we want to access the optional variable we have use either ? or !.

Swift is Code Safe programming language. So, Optional is product from the nil value passing.

?.
Whenever we are trying to access the Optional variable we have to use “?.”. This means we can even get “nil” values.

!.
If we damn sure that the optional variable should have non-nil values then we can use “!” to access the variable.
But, this is not safe. Because, in case of passing nil value to the variable at runtime the app will be crashed.

Eg 1:
Let consider we have one customer class which has protocol methods and we declared the protocol object. And we are conforming the protocol obj by passing the value “self” to the obj. Now the below code will work fine without any issues,

Custom Class and View Controller.
1. Protocol interface:

protocol demoCustomProtocolDelegate {
func cancelTheView ()
func didSelectThePickerItemInView (slectedItem : String)
}

2. Declaring with Optional (?):

var itemPickerViewDelegate : pickerViewProtocolDelegate?

3. In ViewController we are passing value to the protocol object:

customViewObj.demoCustomProtocolDelegate = self

4. Fire the protocol methods by conforming protocol obj:
4.1: We are directly performing the protocol method. It will work fine even, it the protocol obj has nil value. Because, the optional variable will take care of nil values. Even “!.” will also work fine because, the object has value. By using “!” we are unwrappping our selfs.

self.itemPickerViewDelegate?.cancelTheView() (OR)
self.itemPickerViewDelegate!.cancelTheView()

4.2: Here we are unwrapping the optional and checking whether the obj has non-nil value or nil value. If it is non-nil we are performing the action.

if let _ = self.itemPickerViewDelegate
{
self.itemPickerViewDelegate?.cancelThePickerview() (OR)
self.itemPickerViewDelegate!.cancelThePickerview()
}

Now, consider the scenario like if we pass the value as nil to the protocol obj from ViewController

5.     customViewObj.demoCustomProtocolDelegate = nil
6.     self.itemPickerViewDelegate?.cancelTheView().

This will work fine without any issues because, compiler will try to unwrap the optional values and if will realize the value is nil and it will not perform the action.

7.    self.itemPickerViewDelegate!.cancelTheView()

This will crash at run time. Because, we are unwrapping our self from the optional variable but, it has nil value. So, the code will be crash.

Eg: 2

1. var optionalSample :  String?
2. optionalSample = “Value”
print(“Optional Sample: \(optionalSample)”)
O/P: Optionala Sample: Optional(“Value”)
3. By using “!”
optionalSample = “Value”
print(“Optional Sample: \(optionalSample!)”)
Optional Sample: Value
4. By passing nil
optionalSample = nil
print(“Optional Sample: \(optionalSample!)”)
Now, it will be crashed and the Error message is:
fatal error: unexpectedly found nil while unwrapping an Optional value

Hope it will give you some idea on Swift Optional. Please let me know your feedback on this.

Warm Regards,
Yuvaraj Manickam.

Swizzling in iOS

What is Swizzling in iOS?

Method swizzling is the process of changing the implementation of an existing selector. It’s a technique made possible by the fact that method invocations in Objective-C can be changed at runtime, by changing how selectors are mapped to underlying functions in a class’s dispatch table.

Method swizzling is the act of swapping the implementations of two selectors as a program runs.

We have to use runtime class file from objc to swizzle the class file at runtime (i.e: #import <objc/runtime.h>)

+ (void) load method will initiate at the time of app launch. Inside of this method we are going to swizzle (replace) the methods.

For example, Whenever the UIViewController delegate methods getting called, our swizzle methods will be called at the same time. Whenever we are calling our swizzling method it will call the original method.

Here is the sample method swizzling:

1. First create an NSObject class file (Categories) to centralise the method Swizzling

 

NSObject+Swizzle.h

 

#import <Foundation/Foundation.h>

@interface NSObject (Swizzle)

+ (BOOL)swizzleMethods:(SEL)originalSelector withMethod:(SEL)newSwizzleSelector

@end

 

NSObject+Swizzle.m

 

#import “NSObject+Swizzle.h”
#import <objc/runtime.h> // For method swizzling

@implementation NSObject (Swizzle)

+ (BOOL)swizzleMethods:(SEL)originalSelector withMethod:(SEL)newSwizzleSelector
{
Method originalMethod = class_getInstanceMethod(self, originalSelector);
Method newSwizzleMethod = class_getInstanceMethod(self, newSwizzleSelector);

if (originalMethod && newSwizzleMethod) {
if (class_addMethod(self, originalSelector, method_getImplementation(newSwizzleMethod), method_getTypeEncoding(newSwizzleMethod))) {

class_replaceMethod(self, newSwizzleSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, newSwizzleMethod);
}
return YES;
}
return NO;
}

@end

 

 

2. Now it’s time to create class files to Swizzle the methods.
3. For example here am going to Swizzle UIViewController methods like (viewWillAppear and viewDidAppear).
4. Create a new UIViewController Swizzle category class.
5. Do the following in UIViewController+Swizzle class files,

 

UIViewController+Swizzle.h

 

#import <UIKit/UIKit.h>

@interface UIViewController (Swizzle)

@end

 
UIViewController+Swizzle.m

 

#import “UIViewController+Swizzle.h”
#import “NSObject+Swizzle.h”
#import <objc/runtime.h>

@implementation UIViewController (Swizzle)

+ (void) load
{
[self swizzleMethods:@selector(viewDidAppear:) withMethod:@selector(xxx_viewDidAppear:)];
[self swizzleMethods:@selector(viewWillAppear:) withMethod:@selector(xxx_viewWillAppear:)];
}

– (void) xxx_viewWillAppear: (BOOL *) animated
{
[self xxx_viewWillAppear:animated];
}

– (void) xxx_viewDidAppear: (BOOL *) animated
{
[self xxx_viewDidAppear:animated];
}
@end

 
Hope it will give you an idea of method swizzling in iOS. Please let me know if your feedback on this.

Warm Regards,
Yuvaraj Manickam.