在UILabel中垂直排列文本(注意:使用AutoLayout)
我正在复制问题之前询问的同一个问题。 我曾试图给出的解决方案,并没有能够解决它,因为当我使用自动布局sizetofit是无效的。
预期的显示如下所示。
编辑
在我最初的答案中,我使用了标签的段落风格。 原来,对于多行标签,这实际上可以防止标签成为多行标签。 因此我将其从计算中删除。 在Github中了解更多
对于那些使用开放源代码更加舒适的用户,一定要查看TTTAttributedLabel,您可以在其中将标签的文本对齐设置为TTTAttributedLabelVerticalAlignmentTop
诀窍是drawTextInRect
UILabel
并覆盖drawTextInRect
。 然后强制文本在标签边界的原点绘制。
这是您现在可以使用的一个天真的实现:
迅速
@IBDesignable class TopAlignedLabel: UILabel {
override func drawTextInRect(rect: CGRect) {
if let stringText = text {
let stringTextAsNSString = stringText as NSString
var labelStringSize = stringTextAsNSString.boundingRectWithSize(CGSizeMake(CGRectGetWidth(self.frame), CGFloat.max),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil).size
super.drawTextInRect(CGRectMake(0, 0, CGRectGetWidth(self.frame), ceil(labelStringSize.height)))
} else {
super.drawTextInRect(rect)
}
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
layer.borderWidth = 1
layer.borderColor = UIColor.blackColor().CGColor
}
}
斯威夫特3
@IBDesignable class TopAlignedLabel: UILabel {
override func drawText(in rect: CGRect) {
if let stringText = text {
let stringTextAsNSString = stringText as NSString
let labelStringSize = stringTextAsNSString.boundingRect(with: CGSize(width: self.frame.width,height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil).size
super.drawText(in: CGRect(x:0,y: 0,width: self.frame.width, height:ceil(labelStringSize.height)))
} else {
super.drawText(in: rect)
}
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
layer.borderWidth = 1
layer.borderColor = UIColor.black.cgColor
}
}
Objective-C的
IB_DESIGNABLE
@interface TopAlignedLabel : UILabel
@end
@implementation TopAlignedLabel
- (void)drawTextInRect:(CGRect)rect {
if (self.text) {
CGSize labelStringSize = [self.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.frame), CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:@{NSFontAttributeName:self.font}
context:nil].size;
[super drawTextInRect:CGRectMake(0, 0, ceilf(CGRectGetWidth(self.frame)),ceilf(labelStringSize.height))];
} else {
[super drawTextInRect:rect];
}
}
- (void)prepareForInterfaceBuilder {
[super prepareForInterfaceBuilder];
self.layer.borderWidth = 1;
self.layer.borderColor = [UIColor blackColor].CGColor;
}
@end
由于我使用了IBDesignable,因此您可以将此标签添加到故事板并观看它,这就是我看起来的样子
如果不限制UILabel的大小,而不是使用 UILabel中的文本对齐, 只需使用给定标签上的≥约束来更改它的大小。
这是使用Auto Layout的最优雅的解决方案。 不要忘记将numberOfLines设置为零。
您可以使用UITextView而不是UILabel:
取消选中“滚动已启用”
取消选中“可编辑”
取消选中“可选”
将背景颜色设置为ClearColor
上一篇: Vertically align text within a UILabel (Note : Using AutoLayout)