【问题标题】:Custom UIButton setSelected weird behavior自定义 UIButton setSelected 奇怪的行为
【发布时间】:2015-07-12 12:16:04
【问题描述】:

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

我班的代码:

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
    }
}

【问题讨论】:

    标签: ios swift uibutton


    【解决方案1】:

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

    但是如果您将按钮类型设置为自定义,则不会出现此问题

    输出:

    buttonType 找到了一些东西:

    您可能会发现 CocoaBuilder 的线程 How to subclass UIButton? 的讨论很有帮助,尤其是 Jack Nutting's suggestion to ignore the buttonType

    请注意,这种方式 buttonType 没有明确设置为任何东西, 这可能意味着它是 UIButtonTypeCustom。文档没有 似乎实际上指定了这一点,但因为这是 0 中的值 枚举,这很可能会发生(这似乎是可观察的 行为)

    来源:https://stackoverflow.com/a/10278515/3202193

    【讨论】:

    • @AmbroiseCollon :) 欢迎随时欢迎 :)
    • @AmbroiseCollon 您正在查看“tintColor”的结果 - 如果您不想更改为自定义按钮,只需将 tintColor 设置为 clearColor
    猜你喜欢
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多