我正在尝试以编程方式创建适合其内容的UILabel
。
我能做的最好的就是使用NSString's
方法sizeWithAtributes
来获取内容的所需宽度,然后应用将宽度固定为该值的约束。
这是应该使用自动布局完成的方式吗?
最佳答案
如果您需要一些与outoutayouts,我尝试评论:
UILabel *testLabel = [UILabel new];
[testLabel setFont:[UIFont systemFontOfSize:16]];
[testLabel setText:@"Test text for size context"];
[testLabel setTextAlignment:NSTextAlignmentLeft];
[testLabel setNumberOfLines:0]; //0 - infiniy lines if not enough space more
[testLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal]; // Autolayout rule: The higher the priority, the more important hold the text.. by horizontal
[testLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];//some like above but verticale
[testLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];// reverse like Hugging but Compression. then lower priority then text croping.
[testLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisVertical];
[testLabel preferredMaxLayoutWidth:200];//Start new line each 200 points width
[testLabel setPreferredMaxLayoutWidth:YES];// resize Font size by label size.
[testLabel setTranslatesAutoresizingMaskIntoConstraints:NO]; // Disable autolaresize, enable autolayouts