繁体   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