按钮文本颜色不会随 setTitleColor 改变

问题描述 投票:0回答:3

我似乎无法将两个按钮中的文本更改为白色,除非我通过故事板手动执行此操作。有什么想法吗?

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)
    }
}
ios swift uikit uibutton
3个回答
0
投票

如果您在故事板中创建了该按钮。只需转到情节提要中该按钮的属性检查器并确保

1。按钮类型是自定义

2。按钮样式为默认

注意:这也将解决点击时按钮字体设置为系统字体的问题。阅读此答案以供参考。


-1
投票

这应该适合你。

titleLabel.textColor = UIColor.white

-1
投票

如果你想为 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 来使用它

© www.soinside.com 2019 - 2024. All rights reserved.