简体   繁体   中英

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
}

}

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

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.

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 

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM