如何动态增高符合文本条件的指定TableView Cell高度
实现指定条件下的TableView Cell动态高度
核心实现逻辑
借助UITableViewDelegate的heightForRowAt代理方法,根据当前Cell对应的数据判断是否满足匹配条件(name等于"john"),返回不同的高度值,以此实现单个Cell单独增高的效果。
完整代码示例
首先需要准备对应的数据源(假设你用模型存储Cell数据):
// 定义用户模型,包含name字段 struct User { let name: String // 其他需要展示的字段... } // 数据源数组,存储所有Cell要展示的数据 var userDataSource: [User] = []
然后修改并补充TableView的代理方法:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == tableOrder { // 返回数据源的条目数量 return userDataSource.count } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath ) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: PriceTVCell.self)) as? PriceTVCell else { return UITableViewCell() } // 给Cell绑定对应的数据 let targetUser = userDataSource[indexPath.row] cell.nameLabel.text = targetUser.name // 其他字段的赋值逻辑... return cell } // 关键:动态设置Cell高度 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let targetUser = userDataSource[indexPath.row] // 满足条件时返回增高后的高度,否则返回默认高度 return targetUser.name == "john" ? 120 : 80 }
额外优化建议
- 如果你的Cell采用自动布局实现,需要确保内部约束能适配不同高度,此时可以设置
tableView.rowHeight = UITableView.automaticDimension,同时指定tableView.estimatedRowHeight = 80(默认高度),再结合heightForRowAt的条件判断即可。 - 你原代码中延迟设置
tableOrderHeight.constant的方式不够可靠,建议改用KVO监听TableView的contentSize变化来更新高度:
// 在viewDidLoad中添加监听 override func viewDidLoad() { super.viewDidLoad() tableOrder.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil) } // 实现监听回调 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "contentSize" && object as? UITableView == tableOrder { tableOrderHeight.constant = tableOrder.contentSize.height } } // 页面销毁时移除监听 deinit { tableOrder.removeObserver(self, forKeyPath: "contentSize") }
内容的提问来源于stack exchange,提问作者Faheem
相关产品推荐
相关产品推荐

