簡體   English   中英

以編程方式將子視圖添加到自定義UITableViewCell

[英]Add subview to custom UITableViewCell programatically

我有自定義的UITableViewCell並添加了幾個子視圖。 我正在使用Auto Layout 我需要在單元格中添加另一個子視圖,但不使用“ Auto Layout (這樣我就可以用pan gesture左右移動)。 當我添加它時,它得到的高度錯誤(大於所需高度)。 我也在檢查單元格的高度,它小於contentView的高度。 這是我的代碼:

class IntervalCell: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    func createThumb() {

        let height = self.frame.size.height - 20
        let width = height * 0.7
        let originY: CGFloat = 0
        let originX = sliderView.frame.origin.x - width / 2

        let thumbFrame = CGRect(x: originX, y: originY, width: width, height: height)

        let testView = UIView(frame: thumbFrame)
        testView.backgroundColor = .red
        self.contentView.addSubview(testView)

    }

}

因為let height = self.frame.size.height - 20所以假設子視圖的高度只是屏幕的一部分,但實際上它大於整個單元格的高度。 crateThumb被調用tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)

因為你提到crateThumb被調用tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)這意味着你UITableViewCell子類尚未由大小autolayout ,因此你的cell已經高度可以說, 44crateThumb的調用,但在小區大小只有30像素高,因此您的testView將太大。

您可以執行以下操作:

1)調用cell.layoutIfNeeded()調用``crateThumb前()`

2)在您的sublcass layoutSubviews()

override func layoutSubviews() {
    super.layoutSubviews()
    let thumbView = ...//somehow get your thumb view and change its height/width
}

注意:要獲取thumbView,可以將屬性添加到子類或為其分配自定義標簽:

let testView = UIView(frame: thumbFrame)
testView.tag = 100

然后,您可以通過以下方式獲得它:

if let thumbView = contentView.viewWithTag(100) {
      //modify thumbViews height/width
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM