iPhone控件之UILabel

一、UILabel的多行显示问题

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;

posted @ 2012-04-12 21:12  FoxBabe  阅读(297)  评论(0编辑  收藏  举报