Tuesday, 16 February 2016

Multiline UILabel in UITableView with Autolayout - Tutorial



Multiline UILable in UITableView IOS SDK

Creating multi-line UILabel inside cell of UITableView while using auto-layout is a challenging job. In this post, we will learn about creating multi-line UILabel in UITableView while using auto-layout.

With auto-layout, you did not have to take care of cell's height as auto-layout will do this job for you. Before we proceed, please have a look at below requirements that are necessary to follow in order to let auto-layout calculate height for you automatically.

1. All subview's added to TableViewCell's content-view must have top, leading, trailing. bottom constraints.
2. Constraints should be set from top to bottom order.

For video tutorial: https://youtu.be/LRW5notS4XM

Let's start our tutorial. Create a new project and name it "DynamicCellHeight". Open "Main.storyboard" and add UITableView to the view. Add constraints with respect to View. I am setting constraints leading to super-view with no spacing.

Create cell class "DynamicTableViewCell" and add to the project. We will create all are view for cell in this class.

Adding UITableViewCell class
Adding UITableViewCell class
Open "DynamicTableViewCell.xib" . We will now add UILable to our content View. Place UILable to position as shown in the image

Showing UILabel coordinate position with respect to cell's content-view
Showing UILabel coordinate position with respect to cell's content-view
Add top, bottom, leading, trailing constraints as shown below

Constraints added to UILabel
Constraints added to UILabel
Set UILabel's  Prefered width by checkmarking the Explicit checkbox and set number of line to 0.

Setting preffered width to UIlabel
Setting preffered width to UIlabel
Open "DynamicTableViewCell.h" and add IBoutLet for UILabel


@property (nonatomic, weak) IBOutlet UILabel *lblDescription;


Connect, label outlet in xib.  Open "DynamicTableViewCell.m" and  inside awakeFromNib method set preferredMaxLayoutWidth to Label's width as different device have different screen size so we need to update our label width.


- (void)awakeFromNib {
    // Initialization code
    self.lblDescription.preferredMaxLayoutWidth = CGRectGetWidth(self.bounds);
    [self updateConstraints];

}


Open ViewController.h and write delegate and datasource for our UITableView. You can use below code.

ViewController.h

@interface ViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>
{
    NSMutableArray *textArray;

}

ViewController.m


#import "ViewController.h"
#import "DynamicTableViewCell.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    textArray = [[NSMutableArray alloc]initWithCapacity:0];
    
    [textArray addObject:@"This is single line cell."];
     [textArray addObject:@"This is multi line cell. This is multi line cell. This is multi line cell. This is multi line cell. This is multi line cell. This is multi line cell. This is multi line cell. This is multi line cell. This is multi line cell. This is multi line cell. r trtr ytryt rtryr yr yrry ryryryryryr ryryt v bvgf hgfj jfjh fjh fhf hgf fjh f  test tesy  cell. This is multi line cell. This is multi line cell. This is multi line cell. This is multi line cell. r trtr ytryt rtryr yr yrry ryryryryryr ryryt v bvgf hgfj jfjh fjh fhf hgf fjh f  test tesy"];
     [textArray addObject:@"This is single line cell."];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark UITabelView Delegate and Datasource methods

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [textArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellIdentifier = @"cellIdentifier";
    
    DynamicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        cell = (DynamicTableViewCell *)[[[NSBundle mainBundle] loadNibNamed:@"DynamicTableViewCell" owner:self options:nil] objectAtIndex:0];
    }
    
    cell.lblDescription.text = [textArray objectAtIndex:indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    DynamicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    
    if (cell == nil) {
        cell = (DynamicTableViewCell *)[[[NSBundle mainBundle] loadNibNamed:@"DynamicTableViewCell" owner:self options:nil] objectAtIndex:0];
    }
    
    cell.lblDescription.text = [textArray objectAtIndex:indexPath.row];


    cell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.placesTableView.frame), CGRectGetHeight(cell.bounds));

    [cell setNeedsLayout];
    [cell layoutIfNeeded];
    
    
    
    CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return size.height + 1.0f; // Add 1.0f for the cell separator height

}



Now run your code, you will see output like this

OutPut for multiline lable in UITableView with autolayout
OutPut for multiline lable in UITableView with autolayout

Source Code: Download

No comments:
Write comments