简体   繁体   中英

Adding a subview to a UIButton with Auto Layout

I have created a subclass of UIButton . This subclass ( BubbleBtn ) is responsible for adding a UIView to the button.

The view that gets added should be 6 pts from the top, left, and right while spanning half the height of the parent button.

Code:

class BubbleBtn: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        addBubbleView()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        addBubbleView()
    }
    func addBubbleView() {
        setNeedsLayout()
        layoutIfNeeded()
        let bubbleBuffer:CGFloat = 6
        let bubble = UIView(frame: CGRect(x: bubbleBuffer, y: bubbleBuffer, width: self.frame.width - (bubbleBuffer * 2), height: (self.frame.height / 2)))
        bubble.isUserInteractionEnabled = false
        bubble.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.5)
        bubble.layer.cornerRadius = 10
        bubble.layer.zPosition = -1
        self.addSubview(bubble)
    }
}

The problem is, the width and the height of the UIView that gets added is not the correct size; both the width and height fall to short on larger buttons.

How do I add the UIView to the buttons so that the bubble view renders in the proper size?

Screenshot posted below:

子类按钮的自动布局问题

You should set frame by the bounds of the superview and the correct autoresizingMask .

let bubble = UIView(frame: CGRect(x: bubbleBuffer, y: bubbleBuffer,
    width: self.bounds.width - (bubbleBuffer * 2), 
    height: self.bounds.height - (2 * bubbleBuffer))
bubble.translatesAutoresizingMaskIntoConstraints = true
bubble.autoresizingMask = [ .flexibleWidth, .flexibleHeight ]

So bubble adapts its width when the frame of the superview changes.

Try adding constraints for the view inside button.

func addBubbleView() {
   let bubble = UIView()
    bubble.isUserInteractionEnabled = false
    bubble.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.5)
    bubble.layer.cornerRadius = 10
    bubble.layer.zPosition = -1
    self.addSubview(bubble)
    bubble.translatesAutoresizingMaskIntoConstraints = false
    let views = [
        "bubble": bubble
    ]
    var constraints = [NSLayoutConstraint]()
    let vBtnConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|-6-[bubble]-6-|", options: .init(rawValue: 0), metrics: nil, views: views)
    let hBtnConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-6-[bubble]-6-|", options: .init(rawValue: 0), metrics: nil, views: views)
    constraints += vBtnConstraint
    constraints += hBtnConstraint
    NSLayoutConstraint.activate(constraints)
}

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