【问题标题】:How do I calculate the width and height of UIButton given the text and font?给定文本和字体,如何计算 UIButton 的宽度和高度?
【发布时间】:2016-05-08 20:42:58
【问题描述】:

根据this answer,我可以使用intrinsicContentSize自动计算宽度/高度。这就是我所做的,但结果是0, 0

class AutoSizeUIButton: UIButton{
    override func intrinsicContentSize() -> CGSize {
        return CGSizeMake(self.frame.size.width, self.titleLabel!.frame.size.height)
    }
}


networkButton.setTitle("something-here", forState: .Normal)
networkButton.titleLabel?.font = UIFont(name: "HelveticaNeue", size: 20.0)!
let networkSize = networkButton.intrinsicContentSize()
print("button size", networkSize.width, networkSize.height)  //prints 0.0, 0.0

我做错了吗?注意:我不想使用约束。我只想打印宽度/高度。

【问题讨论】:

  • 试试这个代码 UIFont *font = [UIFont fontWithName:@"Helvetica" size:30]; NSDictionary *userAttributes = @{NSFontAttributeName:字体,NSForegroundColorAttributeName:[UIColor blackColor]}; NSString *text = @"你好"; ... const CGSize textSize = [文本 sizeWithAttributes: userAttributes];

标签: ios swift uibutton


【解决方案1】:

试试 networkButton.sizeThatFits。

let networkSize = networkButton.sizeThatFits(CGSizeZero)
print("button size", networkSize.width, networkSize.height)  

(传递给 sizeThatFits 的参数经常被忽略且记录不充分。我不确定 CGSizeZero 是否适用于任何地方 - 也许您应该传递任意大的尺寸)

【讨论】:

    【解决方案2】:

    试试这个:

    networkButton.sizeToFit()
    

    现在网络按钮的大小适合它的文本

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 2010-10-28
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多