简体   繁体   English

Xcode Swift:如何根据按钮的大小动态更改按钮的字体大小?

[英]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. 我知道我可以通过使用自动收缩来动态更改UIlabel的字体大小。 But there's no auto-shrink property for UIbuttons, 但是UIbutton没有自动缩小属性,

so how can I change the font size of my button dynamically according to the size of my button? 那么如何根据按钮的大小动态更改按钮的字体大小?

COde: 码:

import UIKit 导入UIKit

class ViewController: UITableViewController { 类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. UIButton标题显示在UILabel对象中。 So you can set the property by accessing the titleLabel property of UIButton. 因此,您可以通过访问UIButton的titleLabel属性来设置属性。

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. 但是,如果尝试以与按钮标签的大小成正比的方式更改字体大小,则可能必须获取CGRect并根据需要对其进行数学处理。

You have to set minimumScaleFactor property too which specify the smallest multiplier for the current font size. 您还必须设置minimumScaleFactor属性,该属性指定当前字体大小的最小乘数。

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 

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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