ios - 没有 Storyboard 的 Swift UITableViewCell 不使用自动布局

标签 ios swift uitableview autolayout

我正在尝试编写一个没有 Storyboard 的 UITableViewController,其中包含一个定义 UITableViewCell 的类。
我根据需要配置了表格 View

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 200.0  
tableView.register(HomeCell.self, forCellReuseIdentifier: "cell")

并创建了一个仅包含图标的 HomeCell UITableViewCell 类。

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    icon = UIImageView(frame: CGRect.zero);
    icon.translatesAutoresizingMaskIntoConstraints = false;
    contentView.addSubview(icon)
}

我在类中插入了自动布局的函数,并通过调试控制该函数的调用:

override func layoutSubviews() {
    icon.heightAnchor.constraint(equalToConstant: 50).isActive = true
    icon.widthAnchor.constraint(equalToConstant: 50).isActive = true
    icon.leftAnchor.constraint(equalTo: contentView.leftAnchor,
                               constant: 5).isActive = true
    icon.topAnchor.constraint(equalTo: contentView.topAnchor,
                              constant: 5).isActive = true
    contentView.bottomAnchor.constraint(equalTo: icon.bottomAnchor, constant: 5).isActive = true
} 

结果是我的图标位于正确的位置,但 contentView 的高度错误,即 UITableViewAutomaticDimension 设置的原始大小 44,并且连续的行重叠。
有人知道出了什么问题吗?

最佳答案

您应该激活约束a

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    icon = UIImageView(frame: CGRect.zero);
    icon.translatesAutoresizingMaskIntoConstraints = false;
    contentView.addSubview(icon)
    setContr()
} 
func setContr() {

    icon.heightAnchor.constraint(equalToConstant: 50).isActive = true
    icon.widthAnchor.constraint(equalToConstant: 50).isActive = true
    icon.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 5).isActive = true
    icon.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 5).isActive = true
    contentView.bottomAnchor.constraint(equalTo: icon.bottomAnchor, constant: 5).isActive = true
}

关于ios - 没有 Storyboard 的 Swift UITableViewCell 不使用自动布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50229549/

相关文章:

ios - AppDelegate applicationDidEnterBackground 在模拟器上工作但不在设备上工作

ios - 如何读取父节点名称而不从 firebase For ios 获取值

ios - CAPS 页面菜单 : willMoveToPage delegate method getting error

objective-c - 如何循环遍历数组并将 UITableView 中的文本变灰

ios - 应用程序在运行视频一段时间后进入后台模式

ios - UILabel在缩小时会自动设置行数和字体大小

ios - Swift 4+SwiftyJson 自动从 JSON 转换/生成对象

ios - 在通过数据源创建的 UITextField 中显示占位符文本

ios - tableview.reloadData() 上的 UISwitch 约束和动画中断

ios - UIView 框架自动重置