2016-08-23 54 views
0

在我的應用程序中,我有一個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 
     } 
    } 
} 

回答

0

你應該在你viewController實施

optional func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 

並在刷新表格時知道每個單元的高度。

0

cellForRowAtIndexPath必須使用dequeue家庭的方法來讓你的表格單元格實例:

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/#//apple_ref/occ/instm/UITableView/dequeueReusableCellWithIdentifier:forIndexPath

使得對象將通過定期的構造函數來創建,你的工廠方法。你沒有這種靈活性。

所以在你的子類,把你的泛型約束在awakeFromNib或重寫的構造函數。不要忘了考慮並與程式的約束干擾的自動調整大小面具,所以本場必須設置爲false

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instp/UIView/translatesAutoresizingMaskIntoConstraints

最後,cellForRowAtIndexPath內,你可以修改UITableViewCell的制約由出隊調用返回的實例,以獲得您的自定義高度。

祝你好運!

相關問題