MEL*_*WIN 62 cocoa-touch objective-c uilabel ios autolayout
我正在复制问题之前问的相同问题.我曾试图给出的解决方案,并没有能够解决它,因为sizetofit当我使用自动布局是无效的.
预期的显示如下.
Dan*_*sko 131
编辑
在我原来的回答中,我使用的是标签的段落样式.事实证明,对于多行标签而言,这实际上会阻止标签成为多行标签.结果我把它从计算中删除了.在Github中查看更多相关信息
对于那些使用Open Source更加舒服的人,请务必查看TTTAttributedLabel,您可以在其中设置标签的文本对齐方式TTTAttributedLabelVerticalAlignmentTop
诀窍是子类化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
}
}
Run Code Online (Sandbox Code Playgroud)
@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
}
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
由于我使用了IBDesignable,您可以将此标签添加到故事板并观看它,这就是我的样子
Nik*_*vic 40
如果您不限制UILabel的固定大小,而不是在UILabel中对齐文本,只需在给定标签上使用≥约束来更改它的大小.
这是使用自动布局的最优雅的解决方案.不要忘记将numberOfLines设置为零.
art*_*dev 33
您可以使用UITextView而不是UILabel:
取消选中"Scrolling enabled"
取消选中"Editable"
取消选中"Selectable"
将背景颜色设置为ClearColor
归档时间: |
|
查看次数: |
69278 次 |
最近记录: |