ios - 将 UIButton 字体大小调整为宽度

我有以下代码:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0.0, 0.0, 25, 25);

[[button layer] setCornerRadius:5.0f];
[[button layer] setMasksToBounds:YES];
[[button layer] setBackgroundColor:[[UIColor redColor] CGColor]];
[button.titleLabel setFrame:CGRectMake(0,0, 25, 25)];

[button setTitle:[NSString stringWithFormat:@"%@", [[topics objectAtIndex:indexPath.row] unread]] forState:UIControlStateNormal];

问题是当文本中的字符串不长时,它显示正常(1-2位)。但是,当它很长(3++ 位)时,我只能看到一个红色按钮,里面没有文字。我该如何调整?

我不这么认为:

[button.titleLabel setAdjustsFontSizeToFitWidth:YES];

工作,对吧?

最佳答案

试试这个:

button.titleLabel?.numberOfLines = 1
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.lineBreakMode = .byClipping //<-- MAGIC LINE

我不知道为什么会这样,但确实如此:)

https://stackoverflow.com/questions/6178545/

相关文章:

ios - Xcode 9 中的 "This function declaration is not

objective-c - Objective-C 中的 protected 方法

iphone - 以编程方式请求访问联系人

ios - 在 iOS 应用程序中在哪里存储全局常量?

objective-c - 警告 : "format not a string literal an

objective-c - 从 iOS 上的 UIView 将图像保存到应用程序文档文件夹

objective-c - 未找到体系结构 i386 的符号

ios - 如何使用 iOS 轻松调整/优化图像大小?

ios - 将 Project-Swift.h 导入到 Objective-C 类中...找不到文件

objective-c - #import 使用尖括号 < > 和引号 ""