Xcode @IBDesignable按钮背景颜色未在情节提要中呈现

时间:2018-08-27 03:27:16

标签: ios xcode ibdesignable

尝试在情节提要中显示按钮的背景颜色,以下代码正确呈现边框的宽度和半径,但背景不显示。在模拟器中,按钮的背景色正确呈现。

import UIKit

let colorSunset = #colorLiteral(red: 0.9693382382, green: 0.5568749309, blue: 0, alpha: 1)

@IBDesignable class PrimaryButtonA: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        buttonA()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        buttonA()
    }


    func buttonA() {
        self.layer.cornerRadius = 10
        self.layer.borderWidth = 5
        self.layer.backgroundColor = colorSunset.cgColor
    }


}

Code Screenshot

Storyboard Screenshot

Simulator Screenshot

Xcode没有显示任何错误,但是有一个警告是不相关的,它与按钮的固定宽度和高度有关,文本将被剪切。

预先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这是对我有用的解决方案。

import UIKit

let colorSunset = #colorLiteral(red: 0.9693382382, green: 0.5568749309, blue: 0, alpha: 1)

@IBDesignable class PrimaryButtonA: UIButton {

override init(frame: CGRect) {
    super.init(frame: frame)
    buttonA()
}
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    buttonA()
}

override func prepareForInterfaceBuilder() {
    super.prepareForInterfaceBuilder()
    backgroundColor = colorSunset
}


func buttonA() {
    self.layer.cornerRadius = 10
    self.layer.borderWidth = 5
    // self.layer.backgroundColor = colorSunset.cgColor
}

}