自定义 UIButton setSelected 怪异行为

Custom UIButton setSelected weird behavior

我是 swift 的新手,我只是想创建一个 uibutton 的子class。除了当按钮被选中时我有这个奇怪的蓝色圆角矩形出现,如下所示。当我想要的只是一个漂亮的白色边框。

我的代码 class :

import UIKit
import QuartzCore

@IBDesignable
class ColorButton: UIButton {
    //MARK: PROPERTIES
    @IBInspectable var stickerColor: UIColor = UIColor.whiteColor() {
        didSet {
            configure()
        }
    }

    override var selected: Bool {
        willSet(newValue) {
            super.selected = newValue;
            if selected {
                layer.borderWidth = 1.0
            } else {
                layer.borderWidth = 0.0
            }
        }
    }

    //MARK: Initializers
    override init(frame : CGRect) {
        super.init(frame : frame)
        setup()
        configure()
    }

    convenience init() {
        self.init(frame:CGRectZero)
        setup()
        configure()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
        configure()
    }


    override func awakeFromNib() {
        super.awakeFromNib()
        setup()
        configure()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setup()
        configure()
    }

    func setup() {
        //Border color
        layer.borderColor = UIColor.whiteColor().CGColor
        //Corner Radius
        setUpCornerRadius()
    }

    func configure() {
        backgroundColor = stickerColor
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        setUpCornerRadius()
    }

    func setUpCornerRadius() {
        layer.cornerRadius = CGRectGetWidth(bounds) * 0.205
    }
}

我已经检查了你的代码。我遇到了同样的问题。

但是如果你将按钮类型设置为自定义则不会出现这个问题

输出:

找到 buttonType 的内容:

您可以在 CocoaBuilder 的线程中找到讨论 How to subclass UIButton? helpful, particularly Jack Nutting's suggestion to ignore the buttonType:

Note that this way the buttonType isn't explicitly set to anything, which probably means that it's UIButtonTypeCustom. The Docs don't seem to actually specify that, but since that's the 0 value in the enum, that's likely what happens (and that seems to be the observable behavior as well)

来源: