ios - 使用自动布局向 UIButton 添加 subview

标签 ios swift uibutton autolayout subclass

我创建了 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 以适当的大小呈现?

截图如下:

Autolayout problem with subclass button

最佳答案

尝试为 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/

相关文章:

ios - WKWebView 在外部浏览器中打开 PDF

iphone - 如何更改 iOS 中 Navigation Controller 的工具栏颜色?

ios - 我可以让 UIButton 的操作方法接受第二个参数吗?

objective-c - 根据标签更改 UIButton 的颜色

c# - 使用 protobuf-net 反序列化字典

ios - 应用程序在 ios 5.1 中工作正常,但在 ios 6 中崩溃

ios - 通过 plist 覆盖 NSUserDefaults 值

ios - UITableView 没有滚动到最后一行,而是滚动到上面的 5-6 行。 (使用自动布局)

ios - 如何多次使用audioPlayerDidFinishPlaying

ios - 从另一个类访问 UIButton 不起作用?