简体   繁体   中英

Add subview to custom UITableViewCell programatically

I have custom UITableViewCell and have couple of subviews added to it. I am using Auto Layout . I need to add another subview to the cell but without using Auto Layout (so that I can move left and right with a pan gesture ). When I add it it gets wrong height (bigger than wanted). I am inspecting the height of the cell also and it is smaller than the height of the contentView . Here is my code:

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)

    }

}

Because of let height = self.frame.size.height - 20 it is supposed that the subview will have height that is just part of the screen but it actually is bigger than the height of the whole cell. crateThumb is called in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) .

Because you mentioned crateThumb is called in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) it means that your UITableViewCell subclass has not yet been sized by autolayout , thus your cell has height lets say 44 when crateThumb is called but when the cell is sized it is only 30 px in height, thus your testView will be too big.

You can do the following:

1) call cell.layoutIfNeeded() before calling ``crateThumb()`

2) in your sublcass layoutSubviews()

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

Note: to get your thumbView you could add a property to your subclass or assign it a custom tag:

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

Then you can get it with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM