Ios 如何手动加载UITableView
我这里有一个奇怪的布局,有点像这样,也可以看到图片: -UITableViewCell 1 --UIView 2 ----UITableView 3 UITableView 1的控制器如下所示:Ios 如何手动加载UITableView,ios,swift,uitableview,uiview,uikit,Ios,Swift,Uitableview,Uiview,Uikit,我这里有一个奇怪的布局,有点像这样,也可以看到图片: -UITableViewCell 1 --UIView 2 ----UITableView 3 UITableView 1的控制器如下所示: //mainTableView (1) controller var cellHeights = [CGFloat]() func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UIT
//mainTableView (1) controller
var cellHeights = [CGFloat]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let card = CardSource.orangeCards[indexPath.row]
cell.configureCardInCell(card)
cellHeights.insert(card.frame.height + 15, at: indexPath.row)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return cellHeights[indexPath.row]
}
但问题是,当屏幕首次加载时,UIView重叠,因为单元格太小,因为UIView中较小的表视图尚未加载,并且其高度未定义。证明这一点的是,当我滚动到主表视图的底部时,会再次调用cellForRowAt,这两个视图不再重叠,请参见图片。因此,我基本上想要的是一种加载小表视图的方法,在加载大表视图之前定义它的高度,或者如果您有任何其他解决方案,也欢迎这样做
我知道我的问题不是很清楚,我不太擅长解释东西,所以请不要犹豫在评论中问我问题
非常感谢
编辑:
我发现:
static var pharmacyOrangeCard: CardView {
let view = Bundle.main.loadNibNamed("Pharmacy Orange Card", owner: self, options: nil)?.first as! PharmacyTableCardView
print(view.frame.height)
return view
}
打印正确的高度。但是,当我试图从上面的控制器访问它时,它给了我一个较小的数字!同时,我应用了这些约束:
self.translatesAutoresizingMaskIntoConstraints = false
self.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width - 35).isActive = true
card.centerXAnchor.constraint(equalTo: cell.centerXAnchor).isActive = true
card.topAnchor.constraint(equalTo: cell.topAnchor).isActive = true
但我不认为这会影响身高,是吗
编辑2:
好的,我已经改变了这个约束:
self.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width - 35).isActive = true
为此:
card.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 17.5).isActive = true
card.trailingAnchor.constraint(equalTo: cell.trailingAnchor, constant: -17.5).isActive = true
因此,这些约束似乎发挥了作用,因为现在我有了:
顺便说一句,我不知道这是否重要,但我正在为每一张卡使用XIB文件,并且高度不受限制,所以这可能起到了作用
解决编辑问题:
我通过以下方法解决了问题:
override func viewDidAppear(_ animated: Bool) {
mainTableView.reloadData()
}
一旦某个单元格加载到屏幕上,您就无法更改该单元格的高度以获得更好的UI体验 在层次结构中,heightForRowAt在cellForRowAt之前被调用 所以你有两个选择来解决你的问题 首先:在表视图加载单元格之前准备好高度值在将委托值和数据源值设置到表视图之前准备好高度数组 第二:每当您需要更新tableView单元格以根据新高度值重新建立时,请在每次更新高度值后调用此函数 yourTableView.reloadData
您是否尝试过在cellHeights.insertcard.frame.height+15之前使用card.LayoutIded,位于:indexPath.rowYes,configureCardInCell在末尾使用了LayoutIded,但您的意思是card.frame.height在这一点上仍然是错误的?是的,请参见编辑,出现了一些非常奇怪的情况您为什么使用cellHeights.insertcard.frame.height+15,at:indexPath.row so card.frame.height而不是cell.frame.height?