UIButton font size isn't changing

Viewed 2290
private func updateViewFromModel() {
    for index in cardButtons.indices {
        let button = cardButtons[index]
        let card = game.cards[index]
        if card.isFaceUp {
            button.setTitle(emoji(for: card), for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 50)
            button.backgroundColor = .lightGray
        } else {
            button.setTitle("", for: .normal)
            button.backgroundColor = card.isMatched ? .clear : .systemIndigo
        }
        
    }
}

Can anyone tell me what's wrong with this code? title in IB is empty. I successfully set the title. but font size isn't changing.

https://i.stack.imgur.com/lkLjp.png

4 Answers

In Xcode 13 ,UIButton has four type are Plain,Grain,Tinted,Filled .When you create a button in storyboard , button type automatically set with Plain that means new UIButton configurations is on. If you want to old behaviour , you must set style plain to default.

Or , If you want one of the style above . You need to set font like

button.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
  var outgoing = incoming
  outgoing.font = UIFont.systemFont(ofSize: 50)
  return outgoing
 }
yourButton.titleLabel?.font =  UIFont(name: YourfontName, size: 20)

yourButton.titleLabel?.font = .systemFont(ofSize: 12)

I will hope to help you ;)

Following @Omer Tekbiyik Answer Note that the titleTextAttributesTransformer is a parameter of UIButton.Configuration, not UIButton so possible implementation would be:

var config = UIButton.Configuration.plain()
   config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
   var outgoing = incoming
   outgoing.font = UIFont(name: "AlmoniTzarAAA", size: 20) ?? .systemFont(ofSize: 20)
   return outgoing
}

Just change button style from plain to default in storyboard

Related