我有一个固定宽度的UIButton,我想在其中放置文字。由于String的大小事先是未知的,因此当我从平面文件中读取字符串时,我将不得不调整字体大小。我怎样才能做到这一点?类似于以下的功能将很棒:
UIFont resizeFontAs:(UIFont)initialFont andStringAs:(NSString*)string andWidthAs:(int)width
提前致谢
编辑:此代码似乎不起作用:
// Method for creating button, with background image and other properties
- (UIButton *) getCallAgentButtonWithTitleAs:(NSString *)aTitle andImageAs:(UIImage*)bgImg atIndex:(int)index{
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
aButton.frame = CGRectMake(10, 2+index*50, 300, 48);
aButton.titleLabel.frame = CGRectMake(aButton.titleLabel.frame.origin.x + 25.0, aButton.titleLabel.frame.origin.y, aButton.titleLabel.frame.size.width - 50.0, aButton.titleLabel.frame.size.height);
aButton.titleLabel.adjustsFontSizeToFitWidth = YES;
[aButton setTitle:aTitle forState:UIControlStateNormal];
//aButton.titleLabel.font = [UIFont boldSystemFontOfSize:12];
[aButton setTitleColor:UIColorFromRGB(0xFDD428) forState:UIControlStateNormal];
[aButton setBackgroundImage:bgImg forState:UIControlStateNormal];
[aButton addTarget:self action:@selector(callAgent:) forControlEvents:UIControlEventTouchUpInside];
// set the tag as the index and use it later to obtain the phoneNo
[aButton setTag:index];
return aButton;
}
答案 0 :(得分:5)
您可以告诉按钮的标签调整字体本身的大小。
myButton.titleLabel.adjustsFontSizeToFitWidth = YES;
myButton.titleLabel.minimumFontSize = 6.0; // Pick your own value here.
答案 1 :(得分:2)
使用以下方法:
- (CGSize)sizeWithFont:(UIFont *)font
minFontSize:(CGFloat)minFontSize
actualFontSize:(CGFloat *)actualFontSize
forWidth:(CGFloat)width
lineBreakMode:(UILineBreakMode)lineBreakMode
这将允许您指定默认大小(第一个arg)和最小大小,并且必要时将自动缩放字体。