我创建了 UIButton
的子类。此子类 (BubbleBtn
) 负责向按钮添加 UIView
。
添加的 View 应距顶部、左侧和右侧 6 磅,同时跨越父按钮高度的一半。
代码:
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)
}
}
问题是,添加的 UIView
的宽度和高度大小不正确;在较大的按钮上,宽度和高度都会变短。
如何将 UIView 添加到按钮,以便气泡 View 以适当的大小呈现?
截图如下:
最佳答案
尝试为 View 内部按钮添加约束。
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)
}
关于ios - 使用自动布局向 UIButton 添加 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49526187/