[英]Xcode Swift: How to change button font size dynamically according to the size of the button?
我知道我可以通過使用自動收縮來動態更改UIlabel的字體大小。 但是UIbutton沒有自動縮小屬性,
那么如何根據按鈕的大小動態更改按鈕的字體大小?
碼:
導入UIKit
類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標題顯示在UILabel對象中。 因此,您可以通過訪問UIButton的titleLabel屬性來設置屬性。
進一步來說:
yourUIButtonName.titleLabel?.adjustsFontSizeToFitWidth = true
將使字體大小適合按鈕的寬度,並且調整內容插圖將使您能夠填充文本的邊緣。
但是,如果嘗試以與按鈕標簽的大小不成正比的方式更改字體大小,則可能必須獲取CGRect並根據需要對其進行數學處理。
您還必須設置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.