【问题标题】:Table view cell height based upon Dynamic height Table Height issues基于动态高度表高度问题的表视图单元格高度
【发布时间】:2017-07-19 06:17:59
【问题描述】:

场景 -

  1. TableView 的高度是相对于 superview 的高度使用纵横比动态设置的。

  2. TableViewCell 的高度是根据表格视图的高度计算的:

     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
             return tableView.frame.height/2
     }
    

问题 -

最初在委托方法中未正确计算表格视图高度。但在滚动单元格后正确计算。

尝试过的解决方案:

  1. 重新加载tableView 中的viewDidLayoutSubViews()
  2. cellForitemAtIndexPath 中调用cell.layoutSubViews()

有什么解决方案可以正确计算这个 tableView 的高度吗?

【问题讨论】:

  • 是直接返回值tableView.frame.height/2 吗?我认为应该是tableView.frame.size.height/2
  • 你真正想要计算什么?表视图高度或表视图单元高度?您使用的是自动布局,即基于约束的布局还是基于框架的布局?
  • @Mukesh 两者都有效。
  • 请先试用tableView.layoutIfNeeded() ,然后再返回return tableView.frame.size.height/2
  • 为什么你使用动态高度却返回一个恒定的高度?如果您希望它是动态的,您不应该返回UITableViewAutomaticDimension 吗?

标签: ios swift uitableview


【解决方案1】:

请先试用tableView.layoutIfNeeded(),然后再返回return tableView.frame.size.height/2

【讨论】:

  • 尝试早点调用这个,并在返回单元格之前尝试调用cell.contentView.layoutIfNeeded()
  • tableView.layoutIfNeeded() 移出 tableview 委托并将其添加到任何 tableview reload 方法之前。
【解决方案2】:

朋友在vc.h文件中声明CGRect

CGRect tblFrame;

然后在 vc.m viewDidLoad: 方法中将您的 tableView 框架设置为该 tbleFrame,

tblFrame = self.tableView.frame;

那么,

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
             return tblFrame.size.height/2
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-10
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多