简体   繁体   中英

Dynamic height for a UITableViewCell with a dynamic UILabel

I have a UITableViewController that displays a custom UITableViewCell (inherited from UITableViewCell). That same UITableViewCell has a UILabel that can have text of variable length. The challenge I am having is how to access this UILabel in my UITableViewController so that I can set the correct cell height in heightForRowAtIndexPath.

Or on a side note how do I solve my problem of having a dynamicically sized label.

thanks

Here is my code for the custom UITableViewCell:

header:

#import <UIKit/UIKit.h>

@interface MessagesCustomViewCell : UITableViewCell

@property (nonatomic, weak) IBOutlet UILabel *message;   <---- need to access this 

@end

implementation:

#import "MessagesCustomViewCell.h"

@implementation MessagesCustomViewCell
@synthesize message=_message;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end

Using the way of measuring the font size mentioned by Ivan, you could additionally add a class metod to MessagesCustomViewCell,

+ (CGFloat)heightForMessage:(NSString *)message;

in which you calculate the height of message using the appropriate UILabel width/height, font etc. This could be called from heightForRowAtIndexPath: as such:

NSString *dynamicString = [self.mydata objectAtIndex:indexPath.row];
CGFloat height = [MessagesCustomViewCell heightForMessage:dynamicString];
return height;

Call [tableView reloadData] once data is updated.

Check the size with [yourString sizeWithFont:(UIFont*) forWidth(CGFloat) lineBreakMode:(NSLineBreakMode)] method in heightForRowAtIndex. The referred method will return a required size (including the height).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM