我有一个 UIView,可以通过 nib/xib 文件重用。我想加载它并填充一个 UITableViewCell,它将在自动调整大小的 UITableView 中使用。全部带有自动布局。
大多数工作都很好,但似乎加载的 UIView 使用周围添加的约束来缩小 UITableViewCell 的 contentView。这对高度有利,但我不希望对宽度如此。
Ignore the grey cell below, this is just a selected cell.
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cellId = "RowView0002"
var cell = tableView.dequeueReusableCell(withIdentifier: cellId)
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: cellId)
let subView = RowView(frame: cell!.frame)
cell!.contentView.attachViewWithConstraints(subView)
let _ = subView.viewLoadedFromNibAttached(name: cellId)
}
return cell!
}
override public func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 40.0
tableView.rowHeight = UITableViewAutomaticDimension
}
extension UIView
{
public func attachViewWithConstraints(_ view:UIView)
{
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.layoutAttachAll(to: self)
}
@discardableResult
public func viewLoadedFromNibAttached<T : UIView>(name:String) -> T? {
guard let view = Bundle.main.loadNibNamed(name, owner: self, options: nil)?[0] as? T else {
return nil
}
attachViewWithConstraints(view)
return view
}
public func layoutAttachAll(to childView:UIView)
{
var constraints = [NSLayoutConstraint]()
childView.translatesAutoresizingMaskIntoConstraints = false
constraints.append(NSLayoutConstraint(item: childView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1.0, constant: 0))
constraints.append(NSLayoutConstraint(item: childView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1.0, constant: 0))
constraints.append(NSLayoutConstraint(item: childView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0))
constraints.append(NSLayoutConstraint(item: childView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0))
childView.addConstraints(constraints)
}
在 RowView0002.xib 中,我将 rootviews 背景设置为红色,添加了一个带有 4 个约束的 UILabel,其侧面有一些边距,如您所见。我都尝试将 rootView 设置为 RowView 类及其文件所有者。两者都“有效”。
知道如何让 contentView 与 UITableView 匹配吗?
*编辑1:
绿色是 UILabel 的背景。红色是 nib 文件的背景。运行应用程序后,视图继承关系为:UITableViewCell > ContentView > RowView > NibFileView(红色)> UILabel(绿色)
检查视图层次结构表明所有约束均按预期设置。然而 UITableViewContentView 有与所看到的总大小匹配的约束(错误):
self.width = 156.5 @ 1000