在UITableviewCell中设置动态子视图,限制边距
问题描述:
在我的应用程序中,我有一个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
}
}
}
答
你应该在你viewController
实施
optional func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
并在刷新表格时知道每个单元的高度。
答
cellForRowAtIndexPath
必须使用dequeue
家庭的方法来让你的表格单元格实例:
使得对象将通过定期的构造函数来创建,不你的工厂方法。你没有这种灵活性。
所以在你的子类,把你的泛型约束在awakeFromNib
或重写的构造函数。不要忘了考虑并与程式的约束干扰的自动调整大小面具,所以本场必须设置为false
:
最后,cellForRowAtIndexPath
内,你可以修改UITableViewCell
的制约由出队调用返回的实例,以获得您的自定义高度。
祝你好运!