简体   繁体   中英

UIButton subview is offset in subclass

I have a UIButton subclass intended to show a selected state of a button. The selected state simply places a thick black line at the bottom of the button view and when unselected it hides the black line. However, when using this in a UIButton subclass, the black line view is offset. I have tried playing around with insets, but I don't think that is the problem. Here is my subclass:

class TabButton: UIButton {

    private var height:CGFloat = 5
    private var selectedIndicator:UIView?

    override var isSelected: Bool {
        didSet { 
            selectedIndicator?.isHidden = !isSelected 
        }
    }

    fileprivate func initializeSelector(_ frame: CGRect) {
        selectedIndicator = UIView(frame: CGRect(x: 0, y: frame.size.height - height, width: frame.size.width, height: height))
        selectedIndicator?.backgroundColor = UIColor.black 
        self.addSubview(selectedIndicator!)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        initializeSelector(self.frame)
    }
}

The desired button should look like this:

在此处输入图片说明

But instead it looks like this:

在此处输入图片说明

Can anyone help me understand what is happening here and how to fix it? Thanks!

Try this, in layoutSubviews you get the final frame:

override layoutSubviews() {
    super.layoutSubviews()
    selectedIndicator.frame = CGRect(x: 0, y: frame.size.height - height, width: frame.size.width, height: height)
}

The frame of the selectedIndicator is set only once when initializeSelector is called. When the button changes its frame, it does not change the frame of subviews, you need to manually update the frame of selectedIndicator .

To do so, you need to override layoutSubviews() method of UIView .

override layoutSubviews() {
    super.layoutSubviews()
    selectedIndicator?.frame = CGRect(x: 0, y: frame.size.height - height, width: frame.size.width, height: height)
}

See this answer to know when layoutSubviews() is called.

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