将UIButton字体大小调整为宽度 [英] Adjust UIButton font size to width

查看:820
本文介绍了将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 ++数字)时,我只能看到一个红色按钮,里面没有文字。我如何调整?

The issue is that when the string in the text is not long, it shows fine (1-2 digit). However, when it's quite long (3++ digit), all I can see is a red button, with no text inside. How do I adjust this?

我不认为:

[button.titleLabel setAdjustsFontSizeToFitWidth:YES];

完成工作,对吗?

推荐答案

试试这个:

button.titleLabel.numberOfLines = 1;
button.titleLabel.adjustsFontSizeToFitWidth = YES;
button.titleLabel.lineBreakMode = NSLineBreakByClipping; //<-- MAGIC LINE

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

I'm not sure why this does the trick but it does :)

这篇关于将UIButton字体大小调整为宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆