【问题标题】:UiTableview doesn't update sizetofit in iOS 10 but working in iOS 11UiTableview 不会在 iOS 10 中更新 sizetofit 但在 iOS 11 中工作
【发布时间】:2018-04-06 07:15:06
【问题描述】:

我正在创建一个动态 TableView,并在情节提要中设置了行高为 44 的单元格。所以 tableview 的高度将基于我的数据库根据结果返回的行数。同时,我使用 IBOutlet 将 tableView 的底部约束连接到视图。所以 tableview 的高度不会覆盖键盘并与一些配置保持一定的距离。我的问题是如何在 iOS 10 及更低版本中使用 sizeToFits() 更新 tableView.frame.size.height?

这里有一些日志以获得更清晰的图像,tableView and contentView size for iOS 10

当 tableview 的 sizetofit() 永远不会从小到大增加时的另一个图像。 Another logs,如果我的数据库返回 0 结果,它将完全消失,然后 contentSize 将为 0.0,然后当我尝试删除一些文本时,contentSize 将返回 44,因为从数据库中获得了 1 个结果,并且正确的是 SizeToFit( ) 将适合基于 contentSize 的大小。但是在这种情况下,它仍然坚持使用 0.0 并且永远不会更新。

iOS 11 的图像,tableView and contentView size for iOS 11,tableview 的高度为 632 是正确的,因为我确实设置了一些自动布局以防止干扰键盘,因此用户可以在 tableView 中向下滚动。

一些代码便于理解,

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    // configuration for tableViewCell.

    tableView.sizeToFit() // WORKs for iOS 11 but doesn't update for iOS10 

    if UIDevice.current.userInterfaceIdiom == .pad {
        tableView.setNeedsLayout()
        tableView.layoutIfNeeded()
        cell.backgroundColor = UIColor.darkGray
    }

    return cell
}

【问题讨论】:

    标签: swift uitableview sizetofit


    【解决方案1】:

    我不确定你想要达到什么目标。假设您希望您的 tableView 大小与其内容相同,您实际上应该操纵 UITableView 高度的约束。

    您需要在更新 tableView 数据源之后设置高度。 如果您使用的是sizeToFit(),您也应该在更新您的 tableView 数据源

    之后这样做
    // using sizeToFit
    func loadData(){
        allData  = loadFromDatabase()
        tableView.reloadData()
        tableView.sizeToFit()
    }
    

    如果您选择手动计算和设置约束,您可以尝试

    func resizeTableView(){
        allData  = loadFromDatabase()
        tableView.reloadData()
        let tableFrame = tableView.frame
        tableFrame.size.height = tableView.contentSize.height
        tableView.frame = tableFrame
    }
    

    由于使用 sizeToFit 时报告的一些错误,我个人会手动设置框架或设置约束而不是 sizeToFit

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      相关资源
      最近更新 更多