Gui*_*rme 4 shrink nsattributedstring uilabel ios
我有一个宽度有限的标签,我需要它来自动调整文本的字体大小以适应.由于我需要加下划线的文本,我为此标签分配了一个属性字符串:
[_commentsLabel setAttributedText:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%d comments", [comments count]] attributes:@{NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle)}]];
Run Code Online (Sandbox Code Playgroud)
如您所见,注释的数量将定义文本的长度.但出于某种原因,文本并没有缩小.最小字体比例设置为0.1并选中Tighten Letter Spacing.
我认为它可能与我正在使用的自定义字体有关,但即使使用系统默认字体,文本也会被剪裁.
我会尝试设置labels属性
@property(nonatomic) BOOL adjustsFontSizeToFitWidth
Run Code Online (Sandbox Code Playgroud)
到是,看看是否能解决问题.如果没有,请告诉我.我在不同的情况下遇到了问题,但我最终使用了一些代码来手动更改大小.
这是我用来手动更改字体大小的代码.我不知道你的问题是什么,但这最终成为我的问题的一个很好的解决方案.只需在设置标签文本时调用此方法,然后自己设置字体大小.
- (CGFloat)requiredFontSizeForLabel:(UILabel *)label
{
if (!label) {
return kFontSize;
}
CGFloat originalFontSize = kFontSize;
UIFont* font = label.font;
CGFloat fontSize = originalFontSize;
BOOL found = NO;
do
{
if( font.pointSize != fontSize )
{
font = [font fontWithSize: fontSize];
}
if([self wouldThisFont:font workForThisLabel:label])
{
found = YES;
break;
}
fontSize -= 0.5;
if( fontSize < (label.minimumScaleFactor * label.font.pointSize))
{
break;
}
} while( TRUE );
return( fontSize );
}
- (BOOL) wouldThisFont:(UIFont *)testFont workForThisLabel:(UILabel *)testLabel {
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:testFont, NSFontAttributeName, nil];
NSAttributedString *as = [[NSAttributedString alloc] initWithString:testLabel.text attributes:attributes];
CGRect bounds = [as boundingRectWithSize:CGSizeMake(CGRectGetWidth(testLabel.frame), CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin) context:nil];
BOOL itWorks = [self doesThisSize:bounds.size fitInThisSize:testLabel.bounds.size];
return itWorks;
}
- (BOOL)doesThisSize:(CGSize)aa fitInThisSize:(CGSize)bb
{
if ( aa.width > bb.width ) return NO;
if ( aa.height > bb.height ) return NO;
return YES;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2872 次 |
| 最近记录: |