如何检查 UIButton 的 titleLabel 是否超过按钮的框架?

How to check if titleLabel of UIButton exceeds button's frame?

检查 UIButtontitleLabeltext 是否太长以致于实际上超过了按钮的大小以防止出现类似的情况的最佳方法是什么在下面的截图中?我习惯于使用 UILabel 并设置属性 minimumScaleFactoradjustsFontSizeToFitWidth,但是当我尝试使用我的按钮执行此操作时,它似乎没有任何效果:

self.button.titleLabel.minimumScaleFactor = 0.5;
self.button.titleLabel.adjustsFontSizeToFitWidth = YES;

查看 sizetofit() 方法。

self.button.frame = // 在此处设置框架
self.button.sizetofit()
self.button.frame = CGRect(x:self.button.frame.origin.x, y:self.button.frame.origin.y, width:self.button.frame.width, height: yourStandardHeightVariable) //在这里再次设置框架,这部分是为了确保它不会扩展太多

免责声明:此代码未 IDE 测试

你可以像这样在 NSString 中使用 sizeWithAttributes: 方法

NSString *buttonString = @"some string"; // the button's string
    CGSize buttonStringSize = [buttonString sizeWithAttributes:@{NSFontAttributeName : [UIFont fontWithName:<button's font family name> size:<the size of the font>]}];
if (buttonStringSize.width == button.bounds.size.witdh){
  // the text of the button is too long for the button's width, do somthing
}