为什么单击后按钮会发生变化?

Why button changes after the click?

我想将自定义字体设置为 UIButton。我需要以编程方式设置它,因为否则不会应用字体。问题是单击后它变回 built-in 字体。我做错了什么?

import UIKit

class LoginViewController: UIViewController {
    
    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var eyeButton: UIButton!
    @IBOutlet weak var loginButton: UIButton!
    
    var iconClick = true
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loginButton.titleLabel?.font = UIFont(name: "Capitana-Bold", size: CGFloat(16))
    }
    
    @IBAction func iconAction(sender: AnyObject) {
        if (iconClick == true) {
            passwordTextField.isSecureTextEntry = false
            eyeButton.setImage(UIImage(named: "eye-closed"), for: .normal)
        } else {
            passwordTextField.isSecureTextEntry = true
            eyeButton.setImage(UIImage(named:  "eye-open"), for: .normal)
        }
        iconClick = !iconClick
    }
    
    
    @IBAction func onLoginClicked(_ sender: Any) {
       
    }
}

这是一个 iOS 15 填充按钮。你不能通过说

来配置它
loginButton.titleLabel?.font = ...

这在 iOS 14 和之前是可能的(但错误的),但是使用 iOS 15 按钮这是不可能的。要以编程方式配置 Filled 按钮,您必须设置其配置 object.

https://developer.apple.com/documentation/uikit/uibutton/configuration

特别是您想设置按钮配置属性标题。

https://developer.apple.com/documentation/uikit/uibutton/configuration/3750779-attributedtitle

在iOS15你需要使用按钮的配置。这应该有效:

loginButton.configuration?.attributedTitle?.font = UIFont(name: "Capitana-Bold", size: CGFloat(16))