Home > other >  Why button changes after the click?
Why button changes after the click?

Time:10-29

I want to set a custom font to UIButton. I need to set it programmatically because the font is not applied otherwise. The problem is that it changes back to the built-in font after the click. What am I doing wrong?

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) {
       
    }
}

Before After click Config

CodePudding user response:

This is an iOS 15 Filled button. You cannot configure it by saying

loginButton.titleLabel?.font = ...

That was possible (but wrong) in iOS 14 and before, but with an iOS 15 button it is impossible. To configure a Filled button programmatically, you must set its configuration object.

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

In particular you want to set the button configuration attributed title.

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

  • Related