设置自定义UITableViewCells高度

我使用的是自定义UITableViewCell,其中包含一些要显示的标签,按钮和图像视图。单元格中有一个标签,其文本是一个NSString对象,字符串的长度可以是可变的。因此,我无法使用UITableView的heightForCellAtIndex方法为单元格设置恒定的高度。单元格的高度取决于标签的高度,可以使用NSString's sizeWithFont方法确定。我尝试使用它,但好像我在某处出错。如何解决?


这是用于初始化单元格的代码。


if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier])

{

    self.selectionStyle = UITableViewCellSelectionStyleNone;

    UIImage *image = [UIImage imageNamed:@"dot.png"];

    imageView = [[UIImageView alloc] initWithImage:image];

    imageView.frame = CGRectMake(45.0,10.0,10,10);


    headingTxt = [[UILabel alloc] initWithFrame:   CGRectMake(60.0,0.0,150.0,post_hdg_ht)];

    [headingTxt setContentMode: UIViewContentModeCenter];

    headingTxt.text = postData.user_f_name;

    headingTxt.font = [UIFont boldSystemFontOfSize:13];

    headingTxt.textAlignment = UITextAlignmentLeft;

    headingTxt.textColor = [UIColor blackColor];


    dateTxt = [[UILabel alloc] initWithFrame:CGRectMake(55.0,23.0,150.0,post_date_ht)];

    dateTxt.text = postData.created_dtm;

    dateTxt.font = [UIFont italicSystemFontOfSize:11];

    dateTxt.textAlignment = UITextAlignmentLeft;

    dateTxt.textColor = [UIColor grayColor];


    NSString * text1 = postData.post_body;

    NSLog(@"text length = %d",[text1 length]);

    CGRect bounds = [UIScreen mainScreen].bounds;

    CGFloat tableViewWidth;

    CGFloat width = 0;

    tableViewWidth = bounds.size.width/2;

    width = tableViewWidth - 40; //fudge factor

    //CGSize textSize = {width, 20000.0f}; //width and height of text area

    CGSize textSize = {245.0, 20000.0f}; //width and height of text area

    CGSize size1 = [text1 sizeWithFont:[UIFont systemFontOfSize:11.0f]

                        constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];


这是高度和宽度有问题的标签:


textView = [[UILabel alloc] initWithFrame:CGRectMake(55.0,42.0,245.0,ht)];


慕姐8265434
浏览 600回答 3
3回答

慕桂英4014372

您UITableViewDelegate应该实施tableView:heightForRowAtIndexPath:目标C- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    return [indexPath row] * 20;}迅捷5func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {    return indexPath.row * 20}您可能需要使用NSString的sizeWithFont:constrainedToSize:lineBreakMode:方法来计算行高,而不是仅对indexPath进行一些愚蠢的数学运算:)

子衿沉夜

如果所有行的高度都相同,则只需设置rowHeightUITableView 的属性,而不要实现heightForRowAtIndexPath。苹果文档:使用tableView:heightForRowAtIndexPath:而不是rowHeight会对性能产生影响。每次显示表视图时,它都会在委托上为其表的每一行调用tableView:heightForRowAtIndexPath:,这可能导致表视图具有大量行(大约1000或更多)而导致严重的性能问题。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

iOS