Reputation: 3931
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:
Upvotes: 4
Views: 3807
Reputation: 297
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)
}
Upvotes: 2
Reputation: 17722
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.
Upvotes: 1