Skip to main content

UITable view cell dynamic height - ios7 and above

To set the dynamic height of custom table view cell without creating IBOutlet of height constraint, follow the below code: 


@Interface
    __weak IBOutlet UITableView *tblView;
@property (nonatomic, strong) DataViewCustomCell *prototypeCell;



@Implementation

#pragma mark - PrototypeCell
- (DataViewCustomCell *)prototypeCell
{
    if (!_prototypeCell) {
            _prototypeCell = [[[NSBundle mainBundle]loadNibNamed:@"DataViewCustomCell" owner:self options:nil] lastObject];
    }
    return _prototypeCell;
}

#pragma mark - Configure
//Here I put the dummy static string on lblDetailLabel. You can put here the dynamic string

- (void)configureCell:(DataViewCustomCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0)
    {
        cell.lblTitle.text = @"Mobile Insights - Entertainment Report";
        cell.unitedStatsTextLbl.text = @"United States, Q2, 2014";
        cell.lblDetailLabel.text = @"The entertainment industry is a diverse industry covering a wide range of sectors like TV, home entertainment, movies, live events & concerts and digital goods companies. In the US, the audience for entertainment content is large and growing at a rapid rate, thanks to Smartphones and Tablets, which provide anytime -anywhere access to a variety of entertainment content. Smartphones advertising has a significant impact on the way that consumers interact with various forms of entertainment.";
    }
    else  if (indexPath.row==1)
    {
        cell.lblTitle.text = @"Mobile Insights - Entertainment Report";
        cell.unitedStatsTextLbl.text = @"United States, Q1, 2014";
        cell.lblDetailLabel.text = @"Focusing on African Americans and Hispanics, the report takes an in-depth look at the mobile advertising ecosystem, including data related to mobile advertising trends, habits, spending power and more. It shows the importance of multicultural marketing for mobile advertisers, with African Ameri cans and Hispanics showing tremendous growth in population and spending power. The report also emphasizes the significance of accounting for these cultural groups’ unique attitudes and beliefs when implementing mobile video and rich media campaigns.";
    }
    else  if (indexPath.row==2)
    {
        cell.lblTitle.text = @"Mobile Insights - Automotive Industry Report";
        cell.unitedStatsTextLbl.text = @"United States, Q3, 2013";
        cell.lblDetailLabel.text = @"The automotive industry is now the third largest vertical in terms of mobile ad spend on the Vdopia network. This report provides an in-depth analysis of how automotive advertisers have embraced mobile video advertising to target consumers. Focusing on the US market, the report takes a detailed look at a broad spectrum of areas related to auto mobile advertising including demographics (age, gender, ethnicity), auto campaign objectives, type of vehicle advertised, targeting (geo, demo, behavioral) and advertiser type.";
    }
}



#pragma mark - TableView datasource and delegate methods

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        DataViewCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([DataViewCustomCell class])];
        if (cell == nil)
        {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"DataViewCustomCell" owner:self options:nil] lastObject];
        }

        [self configureCell:cell forRowAtIndexPath:indexPath];
        return cell;  
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2) {
        return 270;
    }else{
        
        int currSysVer = [[[UIDevice currentDevice] systemVersion] intValue];
        if (currSysVer >= 8) {
            return UITableViewAutomaticDimension;
        }
        
        [self configureCell:self.prototypeCell forRowAtIndexPath:indexPath];

        [self.prototypeCell updateConstraintsIfNeeded];
        [self.prototypeCell layoutIfNeeded];
        return [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    }
}

///*** Custom table view cell Implementation class
@implementation DataViewCustomCell

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    [self.contentView updateConstraintsIfNeeded];
    [self.contentView layoutIfNeeded];
    
    self.lblDetailLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.lblDetailLabel.frame);
}

Note: The label(sef.lblDetailLabel) who's height will be dynamic, set the below properties in the xib file:
Content hugging priority: Vertical: 250
Content compression resistance priority: Vertical: 751

Comments

Popular posts from this blog

How to kill/exit iOS application on a button click programmatically

I had been practising below code to kill an iOS application. exit(0); But last week, my application was rejected by app store due to following reason: We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines . To avoid any such rebuff, suspend the application using following code snippet. UIApplication.shared.perform(#selector(NSXPCConnection.suspend)) Good news is that now my application is passed the  iOS Human Interface Guidelines and live on app store.

Vector graphics in iOS

In past, designers had to create multiple versions of the same asset (1x, 2x, 3x) to satisfy multiple screen sizes. Using vector assets can save you time because you only have to generate the asset once.  You just need an .xcassets  file in your project for storing your images. In there, you can declare image sets to be “Vectors”. A vector file contains a lot of metadata of an asset that tells the system how to render it's contents, independent of the screen's resolution.  This also means that whenever we get larger screen resolutions, Xcode will be able to scale up your images from your already existing vector PDF for you, giving you automatic support for future devices for free. Steps:- Select “New Image Set” in your  XCAsset. Select the Attributes Inspector in Utilities panel. Under the types drop-down menu, select "Vector" Drag and drop your vector PDF Use the Xcode image catalog image set as you would with any other image. For instance, calling --im

Interview question which I faced during FAANG interview

    Programming question given to me at  leetcode.      Given two strings representing very large integer numbers ("123" , "30") return a string        representing the sum of the two numbers ("153").     The above question can be rephrased as:-            Add two numbers represented by strings            Sum of two large numbers            Add Two Very Large Number (out of range)            How to add two string numbers             Solution in Swift programming language: func add (first: String , second: String ) {         var input1 = first         var input2 = second                  var firstArray = Array (first)         var secondArray = Array (second)                  //both inputs should have same number of characters         var differenceOfCharacter = 0         if firstArray. count > secondArray. count {             differenceOfCharacter = firstArray. count - secondArray. count             ( 0 ..< differenceOfCharacter). forEach