swift UITableView设置rowHeight

tim*_*yng 56 xcode uitableview swift

我试图tableView使用以下代码将每行的高度设置为相应单元格的高度:

override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
      var cell = tableView.cellForRowAtIndexPath(indexPath)
      return cell.frame.height
}
Run Code Online (Sandbox Code Playgroud)

初始化时出现此错误var cell:

线程1:EXC_BAD_ACCESS(代码= 2,地址= 0x306d2c)

Nag*_*jun 130

设置行高有单独的方法:

对于Swift 3

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 100.0;//Choose your custom row height
}
Run Code Online (Sandbox Code Playgroud)

较旧的Swift使用

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 100.0;//Choose your custom row height
}
Run Code Online (Sandbox Code Playgroud)

否则,您可以使用以下设置行高:

self.tableView.rowHeight = 44.0
Run Code Online (Sandbox Code Playgroud)

ViewDidLoad中.


Mun*_*ndi 52

将默认值rowHeight放在viewDidLoad或中awakeFromNib.正如Martin R.指出的那样,你无法打电话cellForRowAtIndexPathheightForRowAtIndexPath

self.tableView.rowHeight = 44.0
Run Code Online (Sandbox Code Playgroud)


Pra*_*hav 11

yourTableView.rowHeight = UITableViewAutomaticDimension
Run Code Online (Sandbox Code Playgroud)

试试这个.

  • UITableView.automaticDimension (2认同)

Ant*_*nio 6

正如评论中指出的那样,你不能cellForRowAtIndexPath在里面打电话heightForRowAtIndexPath.

您可以做的是创建一个用于填充数据的模板单元格,然后计算其高度.此单元格不参与表格渲染,可以重复使用它来计算每个表格单元格的高度.

简而言之,它包括使用您要显示的数据配置模板单元格,使其根据内容调整大小,然后读取其高度.

我从我正在处理的项目中获取了这个代码 - 不幸的是它在Objective C中,我认为你不会在转换为swift时遇到问题

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    static PostCommentCell *sizingCell = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sizingCell = [self.tblComments dequeueReusableCellWithIdentifier:POST_COMMENT_CELL_IDENTIFIER];
    });

    sizingCell.comment = self.comments[indexPath.row];
    [sizingCell setNeedsLayout];
    [sizingCell layoutIfNeeded];

    CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return size.height;
}
Run Code Online (Sandbox Code Playgroud)


Vis*_*iya 5

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            var height:CGFloat = CGFloat()
            if indexPath.row == 1 {
                height = 150
            }
            else {
                height = 50
            }

            return height
        }
Run Code Online (Sandbox Code Playgroud)