我有一个UILabel
,其属性text
我想将文字段落设置为使用NSString
。
我有一个数组,其中存储了一系列代表文本段落的字符。
该段落不必完全符合/包含在此UILabel
中。如果段落没有结束,我会转到下一个标签。
如果我有这个UILabel
160 X 240的矩形大小,我怎么能够确定正确的字体大小才能很好地填充UILabel
的这个字符串?
根据屏幕上矩形的大小,是否有计算字体大小的数学方法?
例如:
UILabel *aLabel = [[UIlabel alloc] initwithFrame(CGRect){{0, 0}, 160, 240}];
aLabel.font = [UIFont fontWithName:@"Courier New" size:<???>]; //(font unit in points)
NSMutableString *aString = [[NSMutableString alloc] init];
//The following tries to fit the character one by one within the label rect based on
//the width and height of the UILabel by appending String
int index = 0;
for(int x = 0; x < 240; x+=<???>) //height of label (pixel unit)
{
for(int y = 0; y < 160; y+=<???>) //width of label (pixel unit)
{
[aString appendWithString:[paragraphArray objectAtIndex:index]];
index++;
}
[aString appendWithString:@\n"]; //line break
}
aLabel.text = aString;
我怎样才能确定???的值?是(for循环的字体大小和像素大小)?
如果这不是执行此类任务的最佳方式,请另外建议我。
答案 0 :(得分:1)
+(void)resizeFontForLabel:(UILabel*)aLabel{
// use font from provided label so we don't lose color, style, etc
UIFont *font = aLabel.font;
float lblWidth = aLabel.frame.size.width;
float lblHeight = aLabel.frame.size.height;
CGFloat fontSize = [font pointSize];
UIFont *newFont = font;
TRC_DBG(@"%@", aLabel.text);
CGFloat height = [aLabel.text sizeWithFont:font constrainedToSize:CGSizeMake(lblWidth,MAXFLOAT) lineBreakMode:aLabel.lineBreakMode].height;
TRC_DBG(@"Label Height %f Constraint height %f", lblHeight, height);
//Reduce font size while too large, break if no height (empty string)
while (height > lblHeight && height != 0) {
fontSize--;
newFont = [UIFont fontWithName:font.fontName size:fontSize];
height = [aLabel.text sizeWithFont:newFont constrainedToSize:CGSizeMake(lblWidth,MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping].height;
TRC_DBG(@"Constrained Height %f", height);
};
TRC_DBG(@"Font size before adjustment %f", aLabel.font.pointSize);
// Set the UILabel's font to the newly adjusted font.
aLabel.font = newFont;
TRC_DBG(@"Adjust to font size of %f", newFont.pointSize);
[aLabel setNeedsLayout];
}
答案 1 :(得分:0)
在故事板中,单击“调整”以适合并选择最小尺寸。