Keon July
Keon July

Reputation: 21

Xcode Swift: How to change button font size dynamically according to the size of the button?

I know I can chagne the font size of an UIlabel dynamically by using auto-shrink. But there's no auto-shrink property for UIbuttons,

so how can I change the font size of my button dynamically according to the size of my button?

COde:

import UIKit

class ViewController: UITableViewController {

@IBAction func myButt(_ sender: UIButton) {}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    myButt.titleLabel?.adjustsFontSizeToFitWidth = true

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell

    return cell
}

}

Upvotes: 2

Views: 9179

Answers (3)

Aravind Vijayan
Aravind Vijayan

Reputation: 155

You have to set minimumScaleFactor property too which specify the smallest multiplier for the current font size.

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        myButt.titleLabel?.adjustsFontSizeToFitWidth = true
        myButt.titleLabel?.minimumScaleFactor = 0.5 

    }

Upvotes: 2

afishershin
afishershin

Reputation: 72

More specifically:

yourUIButtonName.titleLabel?.adjustsFontSizeToFitWidth = true

will fit the font size to the width of the button, and adjusting the content insets will allow you to pad the edges of the text.

However, if you are trying to change the font size in some way that is not directly proportional to the size of the button's label, you will probably have to get the CGRect and math it out as necessary.

Upvotes: 3

jegadeesh
jegadeesh

Reputation: 945

UIButton title is shown in a UILabel object. So you can set the property by accessing the titleLabel property of UIButton.

Upvotes: 1

Related Questions