【问题标题】:Why UITableViewCell dynamic view constraint not working properly?为什么 UITableViewCell 动态视图约束不能正常工作?
【发布时间】:2020-05-31 10:47:48
【问题描述】:

我正在尝试使用以下方式在 UITableViewCell 内创建 UIButton

UITableView 配置:

self.tableView.estimatedRowHeight = 1
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.delegate = self
self.tableView.dataSource = self     

UITableViewCell:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {              
let uiTableViewCell = UITableViewCell(style: .default, reuseIdentifier: "More");
uiTableViewCell.contentView.backgroundColor = .yellow
let moreBtn = UIButton(type: .system)
moreBtn.setTitle("More", for: .normal)
moreBtn.setTitleColor(.white, for: .normal)
moreBtn.backgroundColor = UIColor.init(hexString: "#2A1771")

moreBtn.translatesAutoresizingMaskIntoConstraints = false
uiTableViewCell.contentView.addSubview(moreBtn)

let leading = NSLayoutConstraint(item: moreBtn, attribute: .leading, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .leading, multiplier: 1, constant: 16)
let trailing = NSLayoutConstraint(item: moreBtn, attribute: .trailing, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .trailing, multiplier: 1, constant: 16)
let top = NSLayoutConstraint(item: moreBtn, attribute: .top, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .top, multiplier: 1, constant: 16)
let bottom = NSLayoutConstraint(item: moreBtn, attribute: .bottom, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .bottom, multiplier: 1, constant: 16)

let height = NSLayoutConstraint(item: moreBtn, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 52)

uiTableViewCell.contentView.addConstraints([leading,top,trailing,bottom,height])
NSLayoutConstraint.activate([leading,top,trailing,bottom,height])

return uiTableViewCell

}

请看下面这张图。为什么更多的按钮会从 contentView 中移出

【问题讨论】:

  • 你应该删除let height = NSLayoutConstraint(item: moreBtn, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 52)
  • 删除此行高后仅更改为标准尺寸。但 UIButton 仍然在外面。
  • 标准尺寸是什么意思?
  • UIButton 默认大小。
  • 您的尾随和底部约束应该是 -16,而不是 +16。但是,由于重复使用单元格,您将遇到问题;您应该在单元格本身中添加一次按钮,而不是在cellForRowAt

标签: ios uitableview nslayoutconstraint ios-autolayout


【解决方案1】:

您的约束是说按钮的后沿应该比内容视图后沿多 16(常数为 +16),底部边缘也是如此。

您可以交换这些约束中的itemtoItem 属性,或者使用-16 作为常量。

cellForRow 中添加按钮也会遇到问题,因为当表格视图滚动时会重复使用单元格,从而导致将多个按钮添加到一个单元格中。您应该在单元格本身中添加按钮,无论是在初始化程序中还是在awakeFromNib

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多