vrgrg
vrgrg

Reputation: 616

Why button changes after the click?

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

Upvotes: 6

Views: 1535

Answers (3)

Chinedu Ofor
Chinedu Ofor

Reputation: 767

Setting the button style to default and signInButton.titleLabel?.font = .switzerSemibold(size: CGFloat(K.styles.buttonFontSize))

extension UIFont {
    static func switzerSemibold(size: CGFloat) -> UIFont? {
        return UIFont(name: "Switzer-Semibold", size: size)
    }
    
    static func switzerRegular(size: CGFloat) -> UIFont? {
        return UIFont(name: "Switzer-Regular", size: CGFloat(K.styles.descriptionFontSize))
    }
    
    static func switzerMedium(size: CGFloat) -> UIFont? {
        return UIFont(name: "Switzer-Medium", size: CGFloat(K.styles.buttonFontSize))
    }
}

did the trick enter image description here

Upvotes: 0

Mile Dev
Mile Dev

Reputation: 670

In iOS 15 you need to use configuration for button. This should work:

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

Upvotes: 3

matt
matt

Reputation: 535501

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

Upvotes: 2

Related Questions