我似乎无法将两个按钮中的文本更改为白色,除非我通过故事板手动执行此操作。有什么想法吗?
class AppUIButton: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = Theme.tintColor
layer.cornerRadius = frame.height / 2
setTitleColor(UIColor.white, for: .normal)
}
}
class AddTripViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var tripTextField: UITextField!
@IBOutlet weak var cencelButton: UIButton!
@IBOutlet weak var saveButton: UIButton!
var doneSaving: (() -> ())?
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.font = UIFont(name: Theme.mainFontName, size: 24)
//I can force the text color to change with the bellow
//cencelButton.setTitle("Cancel", for: .normal)
//cencelButton.setTitleColor(UIColor.white, for: .normal)
//saveButton.setTitle("Add", for: .normal)
//saveButton.setTitleColor(UIColor.white, for: .normal)
}
@IBAction func cancel(_ sender: Any) {
dismiss(animated: true)
}
@IBAction func save(_ sender: Any) {
TripFunctions.createTrip(tripModel: TripModel(title: tripTextField.text!))
if let doneSaving = doneSaving {
doneSaving()
}
dismiss(animated: true)
}
}
这应该适合你。
titleLabel.textColor = UIColor.white
如果你想为 UIButton 创建自定义类,你可以这样做
import UIKit
@IBDesignable
class ThemeButton: UIButton {
@IBInspectable var borderRadius:CGFloat = 10.0 {
didSet {
self.layer.cornerRadius = self.borderRadius
}
}
@IBInspectable var fontSize:CGFloat = 14 {
didSet {
self.titleLabel?.font = UIFont.ThemeRegular(ofSize: fontSize)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUI()
// self.isSelected = true
}
override init(frame: CGRect) {
super.init(frame: frame)
setUI()
}
override func prepareForInterfaceBuilder() {
setUI()
}
private func setUI() {
DispatchQueue.main.async {
self.clipsToBounds = true
self.setTitleColor(.white, for: .normal)
self.titleLabel?.font = UIFont.ThemeRegular(ofSize: self.fontSize)
self.backgorundColor = .red
self.layer.cornerRadius = self.borderRadius
}
}
}
您可以通过将按钮类名称赋予 UIButton 来使用它