2017-09-06 161 views
0

我知道我可以通過使用自動收縮來動態改變UIlabel的字體大小。但是沒有UIbuttons的自動收縮屬性,Xcode Swift:如何根據按鈕的大小動態更改按鈕的字體大小?

所以我怎麼能根據我的按鈕的大小動態地改變我的按鈕的字體大小?

代碼:

進口的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 
} 

}

+2

的[調整文本的字體大小,以適應的UIButton]可能的複製(https://stackoverflow.com/questions/32561435/adjust-font-size-of-text-to-fit-in-uibutton ) –

回答

0

更具體地:

yourUIButtonName.titleLabel?.adjustsFontSizeToFitWidth = true 

將適合的字體大小的按鈕的寬度,並調整內容插圖將允許您墊文本的邊緣。

但是,如果您嘗試以某種方式更改字體大小,即而不是與按鈕標籤的大小成正比,您可能必須獲取CGRect並根據需要進行數學運算。

+0

它說:類型'(UIButton) - >()'的值沒有'titileLabel'的成員 –

+0

我可以看到你的代碼,特別是你聲明按鈕和應用'adjustsFontSizeToFitWidth'屬性的地方嗎?它看起來像你不是自己調用UIButton。 – afishershin

+0

是的。我更新了這篇文章。 –

1

UIButton的標題在一個UILabel對象示出。所以你可以通過訪問UIButton的titleLabel屬性來設置屬性。

0

您還必須設置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 

    }