我有一个UIView,它可以通过nib/xib文件重复使用。我想加载这个并填充要在自调整大小的UITableView中使用的UITableViewCell。全部采用自动布局。在UITableViewCell中加载UIView的笔尖文件不能拉伸
大多数作品不错,但它看起来像加载的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背景为红色,加一个UILabel与4个约束它的两侧一定的余量,你可以看到。我都尝试将rootView设置为类RowView以及它的文件所有者。这两个“作品”。
任何想法如何让contentView匹配UITableView?
*编辑1: 绿色是UILabel的背景。红色是笔尖文件的背景。在运行应用程序后,View heirarcy是:UITableViewCell> ContentView> RowView> NibFileView(red)> UILabel(绿色)
检查视图层次结构显示所有约束都按预期设置。然而,UITableViewContentView具有匹配看到的总大小(错误)的约束:
self.width = 156.5 @ 1000
为什么TVC分割线是在不同高度的你的意见结束了吗?看来你的视角占据的高度是单元高度的三倍。你确定这不重叠吗?尝试使用视图调试器检查尺寸 – Andrea
忽略左侧的tableview。这是另一个UITableView。 – Sunkas
有一些我不明白的东西,是你从xib看到的绿色吗? TVC contentView是红色的吗? – Andrea