具有动态UILabel的UITableViewCell的动态高度

时间:2012-10-29 16:15:21

标签: ios ios5 uitableview ios6

我有一个UITableViewController,它显示一个自定义的UITableViewCell(继承自UITableViewCell)。同样的UITableViewCell有一个可以有可变长度文本的UILabel。我遇到的挑战是如何在我的UITableViewController中访问这个UILabel,以便我可以在heightForRowAtIndexPath中设置正确的单元格高度。

或者在旁注上如何解决我有动态尺寸标签的问题。

感谢

以下是我自定义UITableViewCell的代码:

头:

#import <UIKit/UIKit.h>

@interface MessagesCustomViewCell : UITableViewCell

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

@end

实现:

#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

2 个答案:

答案 0 :(得分:3)

使用测量Ivan提到的字体大小的方法,您还可以向MessagesCustomViewCell添加类metod,

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

使用适当的UILabel宽度/高度,字体等计算消息的高度。这可以从heightForRowAtIndexPath调用:如下:

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

答案 1 :(得分:1)

更新数据后调用[tableView reloadData]。

使用heightForRowAtIndex中的[yourString sizeWithFont:(UIFont *)forWidth(CGFloat)lineBreakMode:(NSLineBreakMode)]方法检查大小。引用的方法将返回所需的大小(包括高度)。