所以我有这个UILabel,我希望它自动调整到最大宽度,停止,然后截断。自动调整大小的原因是还有另一个标签(日期),我希望通过一定量的像素(10px)就在右边。
我试图在UILabel上使用一个框架,但这只是静态设置宽度,但这不起作用,我需要这个来自动调整大小......
下面的截图。
答案 0 :(得分:4)
基本思路是在标签不太长的时候使用尺寸来适应,然后在标签太长时“切断”它。它听起来非常简单。
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(32, 96, 90, 16)];
label.backgroundColor = [UIColor greenColor];
label.font = [UIFont fontWithName:@"Helvetica" size:label.frame.size.height];
label.text = @"Johnny Appleseed";
[label sizeToFit];
[self addSubview:label];
const int CUT_OFF_AT_X = 100;
float labelRight = label.frame.origin.x + label.frame.size.width;
if (labelRight > CUT_OFF_AT_X) {
label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, CUT_OFF_AT_X - label.frame.origin.x, label.frame.size.height);
}
labelRight = label.frame.origin.x + label.frame.size.width;
UILabel *badge = [[UILabel alloc] initWithFrame:CGRectMake(labelRight, 96, 90, 16)];
badge.backgroundColor = [UIColor redColor];
badge.font = label.font;
badge.text = @"LEVEL 90";
[badge sizeToFit];
[self addSubview:badge];
答案 1 :(得分:0)
很棒的答案!对于swift 3:
if traitCollection.horizontalSizeClass == .compact && ((lbl_FacilityName.text?.length ?? 0) > 15) {
print("if traitCollection.horizontalSizeClass == .compact and label larger than 15 chars ")
//If label is too long cut the width off at the start of the segmented control -3 for padding
lbl_FacilityName.frame = CGRect(x: lbl_FacilityName.frame.origin.x, y: lbl_FacilityName.frame.origin.y, width: ((segPatientSortControl.frame.origin.x - 3) - lbl_FacilityName.frame.origin.x), height: lbl_FacilityName.frame.size.height)
}