我正在尝试更新包含待办事项标题的 uilabel 框架,以便在没有待办事项描述时它会垂直居中。
这里是cellForRowAt indexPath
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : customCell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customCell
// Configure the cell...
let todo = todos[indexPath.row]
cell.setup(todo: todo.title, todoDescription : todo.todoDescription)
return cell
}
在自定义单元类中:
import UIKit
class customCell: UITableViewCell {
let titleLabel: UILabel! = UILabel(...) //cenvenience initializer setting the uilabel frame
let descriptionLabel: UILabel! = UILabel(...)
func setup(todo : String, todoDescription : String?) {
titleLabel.text = todo
if let todo_descr = todoDescription {
descriptionLabel.text = todo_descr
} else {
descriptionLabel.text = ""
titleLabel.frame = ... //update the frame of the todo title to be centered vertically in the cell, basically change the y of the frame
}
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.frame = ... //initial frame, which is not centered vertically
descriptionLabel.frame = ...
contentView.addSubview(titleLabel)
contentView.addSubview(descriptionLabel)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
当我打印 titleLabel
框架时,它会打印所需的框架属性。但在模拟器中,框架仍然是 layoutSubviews
中赋予标签的框架。
我已经在 setup
函数中尝试了 self.layoutIfNeeded()
但它不起作用。如果存在或缺少待办事项描述,如何更新单元格 subview ?
最佳答案
这种方式代码非常少,设计你的UITableViewCell
如下 Auto Layout Constraints
- 待办事项标题将是静态高度
- 在属性中将 Todo 描述的行数设置为 0。因此,当没有描述时,Todo描述会自动将其高度降低为零。因为我们要添加
UITableViewAutomaticDimension
高度计算方法
然后在 View Controller 中添加这两个数据源方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewAutomaticDimension;
}
关于ios - 更新 UITableViewCell 内的 UILabel 框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41904064/