所以我有一个带有2个原型单元格的TableView。这是我的代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! ItemDetailsCell
cell.centerImage.image = mainImage
cell.heading.text = detailsHeadings[indexPath.row]
let headingString = detailsHeadings[indexPath.row]
cell.body.text = details[headingString]
tableView.rowHeight = cell.labelBlack.frame.height + 40
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell2", forIndexPath: indexPath) as! ItemDetailsCell
cell.heading.text = detailsHeadings[indexPath.row]
let headingString = detailsHeadings[indexPath.row]
cell.body.text = details[headingString]
let bodyString = details[headingString]
let labelWidth = Int(cell.body.frame.width)
println(labelWidth)
let label = UILabel(frame: CGRect(x: 0, y: 0, width: labelWidth, height: 10000))
label.text = bodyString
label.numberOfLines = 100
label.font = UIFont(name: "OpenSans-Light", size: 12.0)
label.sizeToFit()
tableView.rowHeight = label.frame.height + 3
return cell
}
}
因此,第二个原型单元格只有两个标签,其中的值是从Dictionary中分配的。单元格大小需要根据文本行数进行扩展或收缩。在自动布局中,我将行数设置为0,因此它将选择需要多少行。这很好,除非当你在应用程序中滚动时,当用户从底部向上滚动时,它会弹出视图。有办法避免这种情况吗?
提前感谢您的帮助。
我花了更多的时间寻找后发现了这一点
http://candycode.io/automatically-resizing-uitableviewcells-with-dynamic-text-height-using-auto-layout/
它给了我所需要的。我删除了代码中设置rowHeight的部分,然后使用viewDidLoad方法以及自动布局来约束我的单元格大小,经过一番尝试和错误,它在滚动时不会捕捉到位置。
您正在更改表视图的rowHeight。这很可能是错误的。tableView的rowHeight是所有没有自己高度的行的默认值,因此您可以有效地更改所有单元格的高度。
您应该使用委托方法tableView:heightForRowAtIndexPath: