在我的應用程序中,我有一個UITableViewCell
,其中可以包含任意UIView
(或其子類)。我希望看法適合UITableViewCell
的利潤率。細胞高度將根據我的觀點進行調整。在UITableviewCell中設置動態子視圖,限制邊距
我試過各種東西,但沒有積極的結果。
這是代碼。這是行不通的。 :(
它不適合邊距和內容比屏幕尺寸更寬。
怎麼辦?
class CustomView: UIStackView {
class func viewFromNib() -> CustomView {
guard let view = NSBundle(forClass: CustomView.self).loadNibNamed("CustomView", owner: nil, options: nil).first as? CustomView else {fatalError("CustomView not found")}
return view
}
}
class ViewController: UITableViewController {
let customView = CustomView.viewFromNib()
var containerCell: ContainerTableViewCell?
override func viewDidLoad() {
super.viewDidLoad()
containerCell = ContainerTableViewCell.cell(customView, height: nil)
tableView.reloadData()
tableView.estimatedRowHeight = 40
tableView.rowHeight = UITableViewAutomaticDimension
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return containerCell ?? UITableViewCell()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
}
class ContainerTableViewCell: UITableViewCell {
var singleView: UIView?
class func cell(view: UIView, height: CGFloat?) -> ContainerTableViewCell {
let cell = ContainerTableViewCell()
cell.setup(view, height: height)
return cell
}
func setup(view: UIView, height: CGFloat?) {
singleView = view
contentView.addSubview(singleView!)
let margins = contentView.layoutMarginsGuide
singleView?.topAnchor.constraintEqualToAnchor(margins.topAnchor).active = true
singleView?.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor).active = true
singleView?.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor).active = true
singleView?.bottomAnchor.constraintEqualToAnchor(margins.bottomAnchor).active = true
setNeedsLayout()
if let height = height {
contentView.heightAnchor.constraintEqualToConstant(height).active = true
}
}
}