【问题标题】:Dynamic height for a UITableViewCell with a dynamic UILabel具有动态 UILabel 的 UITableViewCell 的动态高度
【发布时间】:2012-10-18 23:53:17
【问题描述】:

我有一个 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

【问题讨论】:

  • 你能发布解决方案吗?我指的是 + (CGFloat)heightForMessage:(NSString *)message;实施。

标签: ios ios5 uitableview ios6


【解决方案1】:

使用Ivan提到的测量字体大小的方法,您可以在MessagesCustomViewCell中额外添加一个类metod,

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

您在其中使用适当的 UILabel 宽度/高度、字体等计算消息的高度。这可以从 heightForRowAtIndexPath: 中调用:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-03
      • 2013-09-02
      • 2017-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多