我有一个具有以下属性的UILabel:
Autoshrinks
到minimum font size
,以避免尽可能地截断文本。Required
(1000)我遇到的问题是标签没有垂直拥抱文字,正如你在下面的图片中看到的那样,顶部有很多空间而且文字低于标题。
我上传了示例项目here。
谢谢!
答案 0 :(得分:0)
请尝试以下代码:
{{1}}
答案 1 :(得分:0)
通过解决方法,我能够达到预期的效果。它不是完美的解决方案,并不适用于所有案例,但它至少解决了我的问题。
<强>概要强>
解决方法的工作原理如下:
actual font
(标签实际使用的字体)。UIViews
&#39; - (UIEdgeInsets)alignmentRectInsets
(reference)修改Autolayout根据实际文字高度定位视图所使用的对齐矩形。有了这一切,我就能从中得到:
到此:
<强>问题强>
<强> CODE 强>
声明了UILabel子类如下
@implementation HuggingLabel
- (UIEdgeInsets)alignmentRectInsets
{
if (self.numberOfLines != 1)
{
if ([super respondsToSelector:@selector(alignmentRectInsets)])
return [super alignmentRectInsets];
else
return UIEdgeInsetsZero;
}
UIFont *fontThatFitsBounds = [self fontThatFitsBounds];
CGSize textSize = [self.text sizeWithAttributes:@{
NSFontAttributeName : fontThatFitsBounds
}];
CGSize actualSize = self.bounds.size;
CGFloat exceedingWidth = actualSize.width = textSize.width;
CGFloat exceedingHeight = actualSize.height - textSize.height;
CGFloat exceedingHeightTop = exceedingHeight / 2.0f;
CGFloat exceedingHeightBottom = MAX(0.0f, exceedingHeight / 2.0f + fontThatFitsBounds.descender);
UIEdgeInsets insets = UIEdgeInsetsMake(
exceedingHeightTop,
0.0f,
exceedingHeightBottom,
0.0f
);
return insets;
}
- (UIFont *)fontThatFitsBounds
{
CGSize currentSize = CGSizeZero;
CGFloat fontSizeThatFits = self.font.pointSize + 1.0f;
do {
fontSizeThatFits = fontSizeThatFits - 1.0f; //try with one point smaller size
NSDictionary *attributes = [self stringAttributesWithFontOfSize:fontSizeThatFits];
currentSize = [self.text sizeWithAttributes:attributes];
} while (currentSize.width > self.bounds.size.width ||
currentSize.height > self.bounds.size.height);
return [self.font fontWithSize:fontSizeThatFits];
}
- (NSDictionary *)stringAttributesWithFontOfSize:(CGFloat)fontSize
{
NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = self.lineBreakMode;
paragraphStyle.alignment = self.textAlignment;
NSDictionary *attributes = @{
NSFontAttributeName : [self.font fontWithSize:fontSize],
NSParagraphStyleAttributeName : paragraphStyle
};
return attributes;
}
@end
可以下载here
的演示项目