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;
UILable显示文字,大多数情况下文字是动态的,所以UILable的大小需要自适用,下面是实现的具体代码:
myLable=[[UILabel
alloc] initWithFrame:CGRectMake(0, 23, 175, 33)];
[myLable setFont:[UIFont fontWithName:@"Helvetica" size:10.0]];
[myLable setNumberOfLines:0];
[myLable setBackgroundColor:[UIColor clearColor]];
[myAdView addSubview:myLable];
UIFont *font = [UIFont fontWithName:@"Helvetica" size:10.0];
CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(175.0f, 2000.0f) lineBreakMode:UILineBreakModeWordWrap];
CGRect rect=myLable.frame;
rect.size=size;
[myLable setFrame:rect];
[myLable setText:text];