2016-11-22 66 views
0

我有一個單元格,其內容可以與其他單元格不同(其他單元格屬性相同) - 我認爲自定義視圖支持在這種情況下,筆尖可以很好地工作,但遇到了使用自定義視圖的問題,其中高度是動態的單元格。在IB中使用XIB自定義視圖uitableviewcell w /動態高度

故事板:

enter image description here

這裏是一個UITableView和一個自定義的UITableViewCell,MessageTableViewCell,這樣實現的一個UIViewController:

class MessageTableViewCell: UITableViewCell { 

@IBOutlet weak var avatar: UIImageView! 
@IBOutlet weak var initials: UILabel! 
@IBOutlet weak var timestamp: UILabel! 
@IBOutlet weak var messageView: UIView! 

override func awakeFromNib() { 
    super.awakeFromNib() 
    // Initialization code 
} 

override func setSelected(_ selected: Bool, animated: Bool) { 
    super.setSelected(selected, animated: animated) 

    // Configure the view for the selected state 
} 

} 

在視圖控制器的cellForRowAtIndexPath方法,我嘗試使用messageView(視圖控制器單元格中的白色框)的框架來實例化一個由xib支持的UIView。

該自定義視圖:

enter image description here

它的實現:

類消息查看:NibLoadingView {

@IBOutlet weak var message: UILabel! 

} 

的NibLoadingView實現: (來源:https://stackoverflow.com/a/40051928/4096655

class NibLoadingView: UIView { 

weak var view: UIView! 

override init(frame: CGRect) { 
    super.init(frame: frame) 
    nibSetup() 
} 

required init?(coder aDecoder: NSCoder) { 
    super.init(coder: aDecoder) 
    nibSetup() 
} 

private func nibSetup() { 
    backgroundColor = .clear 

    view = loadViewFromNib() 
    view.frame = bounds 
    view.autoresizingMask = [.flexibleWidth, .flexibleHeight] 
    view.translatesAutoresizingMaskIntoConstraints = true 

    addSubview(view) 
} 

private func loadViewFromNib() -> UIView { 
    let bundle = Bundle(for: type(of: self)) 
    let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle) 
    let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView 

    return nibView 
} 
} 

爲行實現細胞:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell") as? MessageTableViewCell else { 
     return UITableViewCell() 
    } 

    let frame = cell.messageView.frame 
    let messageView = MessageView(frame: frame) 
    messageView.message.text = messages[indexPath.row] 
    cell.addSubview(messageView) 

    return cell 
} 

結果:

enter image description here

簡短的故事,我想什麼之間我通常會考慮不同的一些共同的特性細胞,並試圖爲不同的單元格部分創建自定義視圖,其中一些具有動態高度。謝謝閱讀。

回答

0

你並不需要創建一個自定義視圖MessageView,而不是你需要添加的消息查看MessageView的內容是你在對的viewController原型細胞MessageTableViewCell添加的看法,不要忘了網點,並在messageView約束內給出標籤頂部,頂部,尾部和底部, 最後在您的viewController而不是調用tableView(_:heightForRowAt:)調用tableView(_:estimatedHeightForRowAt:) UITableViewDelegate方法。

+0

問題是MessageView應該可以與其他視圖互換。否則,我只需要在IB中完成我需要的每種不同類型的單元。 –

+0

@thefredelement好了,然後只需將正確的約束添加到MessageView中的標籤,並調用tableView(_:estimatedHeightForRowAt:)',以便單元格高度動態增加。 –

相關問題