关于UILabel的多行显示 UILabel numberOfLines



早上做了会实验结果如下:

1.N行完全自适应:
        UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 100, 21)];
        NSString *txt = @"dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
        testLabel.numberOfLines = 0; ///相当于不限制行数
        testLabel.text = txt;
这样不行,还需要调用 [testLabel sizeToFit];


2.限制在N行内自适应:
        UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 100, 21)];
        NSString *txt = @"dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
        testLabel.numberOfLines = 3;   限制在3行内自适应
        testLabel.text = txt;
     [testLabel sizeToFit];
结果不起作用,全部在一行显示了。

3.为了实现2的需求,需要这么做:
        CGSize maxSize = CGSizeMake(100, 21*3);
        UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 100, 21)];
        NSString *txt = @"dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
        CGSize labelSize = [txt sizeWithFont:testLabel.font constrainedToSize:maxSize lineBreakMode: UILineBreakModeTailTruncation];

        testLabel.frame = CGRectMake(testLabel.frame.origin.x, testLabel.frame.origin.y, labelSize.width, labelSize.height);
        testLabel.text = txt;

完事...



你可能感兴趣的:(UILabel,numberOfLines)