【问题标题】:Xcode Swift: How to change button font size dynamically according to the size of the button?Xcode Swift:如何根据按钮的大小动态更改按钮字体大小?
【发布时间】:2018-02-14 11:44:38
【问题描述】:

我知道我可以通过使用自动收缩来动态改变 UIlabel 的字体大小。但是 UIbuttons 没有自动收缩属性,

那么如何根据按钮的大小动态更改按钮的字体大小?

代码:

导入 UIKit

类视图控制器: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
}

}

【问题讨论】:

标签: ios swift xcode uibutton storyboard


【解决方案1】:

更具体地说:

yourUIButtonName.titleLabel?.adjustsFontSizeToFitWidth = true

将使字体大小适合按钮的宽度,调整内容插入将允许您填充文本的边缘。

但是,如果您尝试以某种方式更改字体大小,而 与按钮标签的大小不成正比,您可能需要获取 CGRect 并将其计算为必要的。

【讨论】:

  • 它说:类型'(UIButton) ->()'的值没有'titileLabel'的成员
  • 我可以看看您的代码,特别是您声明按钮的位置以及应用adjustsFontSizeToFitWidth 属性的位置吗?看起来您并没有自己调用 UIButton。
  • 现在的写法,第一行创建了一个函数 myButt()。因此,myButt.titleLabel? 将不存在——该函数没有这样的成员。要正确引用按钮,您需要为按钮创建一个@IBOutlet,它将获取按钮本身,而不是创建函数。为此,您可以 Ctrl + 从按钮本身或 Connections 侧面板中的“新引用插座”拖动按钮到 ViewController 类中。这应该允许您访问.titleLabel 组件。
  • 谢谢。在我用 IBOutlet 替换 IBAction 后它起作用了。
【解决方案2】:

UIButton 标题显示在 UILabel 对象中。所以你可以通过访问 UIButton 的 titleLabel 属性来设置属性。

【讨论】:

    【解决方案3】:

    您还必须设置 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 
    
        }
    

    【讨论】:

      猜你喜欢
      • 2022-12-10
      • 2012-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多