2

所以我有这个 UILabel 我想让它自动调整到最大宽度,停止,然后截断。自动调整大小的原因是有另一个标签(日期),我想在它的右侧设置像素量(10px)。

我试图在 UILabel 上使用一个框架,但这只是静态设置宽度,但这不起作用,我需要它来自动调整大小......

截图如下。

在此处输入图像描述

4

2 回答 2

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];
于 2013-06-07T03:54:21.920 回答
0

很好的答案!对于迅捷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)
     }
于 2017-05-11T15:15:34.647 回答