ios - 更新 UITableViewCell 内的 UILabel 框架

标签 ios swift uitableview

我正在尝试更新包含待办事项标题的 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

UItableViewCell Design

  1. 待办事项标题将是静态高度
  2. 在属性中将 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/

相关文章:

ios - 在 UILabel 中读取\n

Xcode 7.1 - Storyboard中的原型(prototype)单元格未显示

arrays - 将不同的自定义单元格类型放入表格 View 中

iOS 内容从水平到垂直动画,反之亦然

iOS11 AppIcon无法改变

swift - Guard let 不区分输入

mysql - MySQL 存储过程中每次迭代后暂停的循环是否会在暂停期间保持锁定?

ios - 关于 "location-based APIs for emergency services"上的苹果拒绝

ios - 带搜索栏的 TableView Controller 和创建数据库

swift - 存储弱引用有时会导致泄漏