【问题标题】:How to Increase TableCell Height When Content Added Programmatically?以编程方式添加内容时如何增加表格单元格的高度?
【发布时间】:2016-05-26 10:10:22
【问题描述】:

我正在开发一个应用程序。我有一些来自服务器的数据。

现在我不知道行的数据计数。我只知道Fields的名字。

我想在UITableViewCell 中显示这些数据。

我有一个自定义TableCell。我在里面放了一个ContentView。 我设置了以下约束:

     - Leading
     - Trailing 
     - Top
     - Bottom

在我的ViewController's DidLoad 方法中,我有这个代码:

    UINib *nib = [UINib nibWithNibName:cellName bundle:nil];
   [[self mTableView] registerNib:nib forCellReuseIdentifier:cellName];


     self.mTableView.rowHeight = UITableViewAutomaticDimension;
    self.mTableView.estimatedRowHeight = 100.0;

我正在创建UILabel 像这样

      - (void)awakeFromNib {
[super awakeFromNib];


CGFloat ypos = 0;

for(int i=0;i<6;i++)
{
    UILabel *lbl  = [[UILabel alloc]init];
    lbl.backgroundColor= [UIColor redColor];
    lbl.frame = CGRectMake(0,ypos,30,10);

    [self addSubview:lbl];
    ypos += 16;
}

[self setNeedsLayout];
[self layoutIfNeeded];

// Initialization code
}

这是我的 CustomCell。但我的 TableCell Hegiht 没有增加。

请任何人告诉我我缺少什么?

【问题讨论】:

  • contentView(我希望您在谈论添加到单元格内容视图的 UIView 子类)约束在哪里。 ?
  • 您需要为标签设置约束,并将 numbersOfLine 设置为零。它会自动增加标签高度。
  • @vikash1307 兄弟,我正在以编程方式创建它们
  • 那么,你也可以做兄弟。
  • 请在这里查看我的答案:stackoverflow.com/questions/37235605/…

标签: ios objective-c xcode uitableview autolayout


【解决方案1】:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dict1 = (NSDictionary*)[array objectAtIndex:indexPath.row];
    NSString *cellText = [dict1 valueForKey:@"test"];
    UIFont *cellFont = [UIFont fontWithName:FONT_NAME_GOTHAM_4 size:11.0];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];

    return labelSize.height + 80;
}

【讨论】:

  • 这段代码是做什么的? sizeWithFont: 现已弃用。
  • 这是我最后的希望..我不想让代码变得庞大,这就是为什么我正在寻找更好的方法。感谢您的解决方案
【解决方案2】:

到目前为止,您做得对。但不要忘记使用 tableView 的委托/数据源 - cellForRowHeight

此外,正如 Lion 所提到的,您需要为标签添加约束。如果您以编程方式执行标签,那么也以编程方式执行自动布局。

【讨论】:

    猜你喜欢
    • 2011-04-08
    • 2014-02-19
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    相关资源
    最近更新 更多