[英]How to set selected image of UIButton in XCode Interface Builder
[英]How to set a default title in UIButton subclass that works in Interface Builder (Xcode 9)
我有一個在整個應用程序中重復的按鈕,因此我創建了一個子類以避免每次都必須設置所有基本屬性。
我可以設置背景顏色、文本顏色、圓角。
但是,當我嘗試設置默認標題時,事情就分崩離析了——不是“按鈕”。 在 Interface Builder 中,它會忽略標題,但也會忽略字體顏色,這在我未設置標題時有效。
如果我運行該應用程序,一切看起來都不錯,但使用 Interface Builder 的一個主要目的是省去不斷運行應用程序以檢查基本 UI 布局的步驟。
這是子類。 請注意,如果您注釋掉 2 個 setTitle 行,該按鈕將顯示正確的文本顏色(白色)。
import UIKit
@IBDesignable class ContinueButton: UIButton {
@IBInspectable var titleColour: UIColor = .white {
didSet {
setTitleColor(titleColour, for: .normal)
}
}
@IBInspectable var bgColour: UIColor = UIColor.gray {
didSet {
backgroundColor = bgColour
}
}
@IBInspectable var buttonTitle: String = "Continue" {
didSet {
setTitle(buttonTitle, for: .normal)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setAttributes()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setAttributes()
}
public func setAttributes() {
setTitleColor(titleColour, for: .normal)
backgroundColor = bgColour
setTitle(buttonTitle, for: .normal)
}
override public func layoutSubviews() {
super.layoutSubviews()
setAttributes()
layer.cornerRadius = 0.5 * bounds.size.height
clipsToBounds = true
}
}
ps,我的主要目標是創建一個可重用的自定義按鈕,負責設置一堆默認值。 如果有更好的方法來實現這一點,我會很高興聽到這個消息 - 特別是如果它可以通過視覺而不是通過代碼來完成。
感謝您提供的任何建議,
-妮可
只需覆蓋 prepareForInterfaceBuilder() 並添加 setAttributes()。
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setAttributes()
}
tintColor
屬性可以解決問題。 button.tintColor = UIColor.red
但要確保覆蓋prepareForInterfaceBuilder()
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
button.tintColor = UIColor.red
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.