UITableViewAutomaticDimension直到滚动才能工作

jja*_*tie 24 uitableview uikit ios swift

首次加载表视图时,所有可见单元格都是estimatedRowHeight.当我向下滚动时,单元格会自动调整大小,当我向上滚动时,最初估计的单元格正在自动调整大小.

一旦细胞自动调整大小,它们似乎永远不会再回到估计的高度.

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)
    self.tableView.estimatedRowHeight = 80.0
    self.tableView.rowHeight = UITableViewAutomaticDimension

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
Run Code Online (Sandbox Code Playgroud)

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cellIdentifier = "Cell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as CustomTableViewCell

    // Configure the cell...
    let restaurant = restaurants[indexPath.row]
    cell.namelabel.text = restaurant.name
    cell.locationlabel.text = restaurant.location
    cell.typelabel.text = restaurant.type
    cell.thumbnailImageView.image = UIImage(named: restaurant.image)
    cell.thumbnailImageView.layer.cornerRadius = cell.thumbnailImageView.frame.size.width / 2
    cell.thumbnailImageView.clipsToBounds = true
    cell.accessoryType = restaurant.isVisited ? .Checkmark : .None

    return cell
}
Run Code Online (Sandbox Code Playgroud)

关于如何让细胞最初自动化的想法?

更新:从Xcode 7 beta 6开始,这不再是一个问题

Bla*_*ank 26

加载表后,只需调用"reloadSections":

self.tableView.reloadSections(NSIndexSet(indexesInRange: NSMakeRange(0, self.tableView.numberOfSections())), withRowAnimation: .None)
Run Code Online (Sandbox Code Playgroud)

或者在Swift 3中:

let range = Range(uncheckedBounds: (lower: 0, upper: self.tableView.numberOfSections))
self.tableView.reloadSections(IndexSet(integersIn: range), with: .none)
Run Code Online (Sandbox Code Playgroud)

  • 这是一个解决方案,但它不应该是必要的. (4认同)
  • 可悲的是,甚至认为我现在已经重建了自己的约束至少5次,我开始认为这是Apple的UITableViewAutomaticDimension实现中的一个错误.它似乎是自动添加高度约束,使细胞膨胀或收缩,当重新使用细胞时,它会起作用...... (3认同)

eul*_*ule 8

我遇到了同样的问题,并发现配件 cell.accessoryType混乱时会自动调整大小None,所以它现在看起来像Xcode中的一个错误.

但正如@Blankarsch所说,reloadSections(..)如果您需要配件,呼叫有助于解决此问题.

  • 使用Xcode 7 beta 6,此问题不再存在. (2认同)

rob*_*408 6

我认为这里的答案副作用较少.具体地添加cell.layoutIfNeeded()tableView:cellForRowAtIndexPath:

我也正在做@nosov建议的良好做法,但没有测试他们是否需要同时完成.


Nos*_*vel 5

只是像这样覆盖estimatedHeightForRowAtIndexPath

(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
Run Code Online (Sandbox Code Playgroud)

并在CustomTableViewCell视图中检查您的autoLayout约束.