iOS:UITableViewCell的动态高度

时间:2016-05-04 08:30:30

标签: objective-c uitableview ios9 uitableviewautomaticdimension

我正在使用iOS9 XCode7 我需要根据labelText Height

动态更改单元格的高度

我用过:

self.tableView.rowHeight=UITableViewAutomaticDimension;

但它不适用于定制电池。 iOS9中删除了sizetoFit

请提出建议。 感谢

3 个答案:

答案 0 :(得分:13)

相对于单元格,顶部,底部,左侧和右侧给出标签约束。

比您的单元格大小将随内容高度增长。

也使您的标签成为多行。(通过在属性检查器中将Lines属性设置为0)

#pragma mark- Menu table Delegates 

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return UITableViewAutomaticDimension;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return UITableViewAutomaticDimension;
}

答案 1 :(得分:1)

我不太清楚这句话意味着什么(截图会有帮助):

"我需要根据labelText高度动态更改单元格的高度"

因此,您有一个UITableViewCell,其中包含UILabel,并希望您的表格中的每个单元格都具有高度,具体取决于该单元格的标签?

这是我使用的代码。

在我的UITableViewCell课程中,我将定义一个要测量的静态函数,并返回我的.xib文件的高度:

@implementation MikesTableViewCell

...

+(CGSize)preferredSize
{
    static NSValue *sizeBox = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // Assumption: The XIB file name matches this UIView subclass name.
        NSString* nibName = NSStringFromClass(self);
        UINib *nib = [UINib nibWithNibName:nibName bundle:nil];

        // Assumption: The XIB file only contains a single root UIView.
        UIView *rootView = [[nib instantiateWithOwner:nil options:nil] lastObject];

        sizeBox = [NSValue valueWithCGSize:rootView.frame.size];
    });
    return [sizeBox CGSizeValue];
}

@end

然后,在我的UIViewController课程中,我会告诉我UITableView使用此单元格,找出它的高度。

@property (nonatomic) float rowHeight;

UINib *cellNib = [UINib nibWithNibName:@"MikesTableViewCell" bundle:nil];
[self.tableView registerNib:cellNib forCellReuseIdentifier:@"CustomerCell"];

rowHeight = [MikesTableViewCell preferredSize].height;

...

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (float)rowHeight;
}

同样,这可能不是您正在寻找的,但我希望这会有所帮助。

答案 2 :(得分:1)

试试这个。 它很简单。

在heightForRowAtIndexPath方法中设置此高度

  float vendorNameHeight = [vendorNameLbl.text heigthWithWidth:width andFont:[UIFont fontWithName:@"Signika-Light" size:21.0]];

然后

  UILabel*vendorNameLbl=[[UILabel alloc]initWithFrame:CGRectMake( 13, 11, 100, 22)];
  vendorNameLbl.numberOfLines = 0;
  [vendorNameLbl sizeToFitVertically];
相关问题