Reputation: 21
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
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
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
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