【发布时间】:2017-06-10 15:37:37
【问题描述】:
我有一个可通过 nib/xib 文件重复使用的 UIView。我想加载它并填充一个 UITableViewCell,它将用于自调整大小的 UITableView。全部自动布局。
大多数都很好,但似乎加载的 UIView 使用它周围添加的约束来缩小 UITableViewCell 的 contentView。这对高度有好处,但我不希望这样的宽度。
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 文件的背景。运行应用程序后,View heirarcy 是: UITableViewCell > ContentView > RowView > NibFileView (red) > UILabel (green)
检查视图层次结构表明所有约束都按预期设置。但是 UITableViewContentView 的约束与看到的总大小相匹配(错误):
self.width = 156.5 @ 1000
【问题讨论】:
-
为什么 TVC 分隔线与视图末端的高度不同?看来您的视图占据的高度是单元格高度的三倍。你确定这不是重叠的吗?尝试使用视图调试器检查尺寸
-
忽略左边的tableview。这是另一个 UITableView。
-
有些东西看不懂,绿色是你从xib看的吗?红色是 TVC contentView 吗?
-
绿色是UILabel的背景。红色是 nib 文件的背景。运行应用程序后,View heirarcy 是: UITableViewCell > ContentView > RowView > NibFileView (red) > UILabel (green)
-
标签的拥抱和抵抗优先级是否设置为默认值?
标签: ios uitableview autolayout uitableviewautomaticdimension