有没有办法在UILabel中像UITextView中那样有多行文本或者我应该用第二行代替?


当前回答

在下面的代码或故事板本身中设置

Label.lineBreakMode = NSLineBreakByWordWrapping; 标签行数 = 0;

请不要忘记为标签设置左、右、上、下约束,否则它将无法工作。

其他回答

这些东西帮助了我

更改UILabel的这些属性

label.numberOfLines = 0;
label.adjustsFontSizeToFitWidth = NO;
label.lineBreakMode = NSLineBreakByWordWrapping;

在输入字符串时使用\n在不同的行中显示不同的单词。

例子:

 NSString *message = @"This \n is \n a demo \n message for \n stackoverflow" ;

在这个函数中,传递你想在label中赋值的字符串,并传递字体大小来代替self。activityFont和传递标签宽度的地方235,现在你得到标签高度根据你的字符串。 它会工作得很好。

-(float)calculateLabelStringHeight:(NSString *)answer
{
    CGRect textRect = [answer boundingRectWithSize: CGSizeMake(235, 10000000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.activityFont} context:nil];
    return textRect.size.height;

}

我找到的最好的解决方案(解决一个本来应该在框架中解决的令人沮丧的问题)与vaychick的类似。

只需在IB或代码中将行数设置为0即可

myLabel.numberOfLines = 0;

这将显示所需的行,但将重新定位标签,使其水平居中(以便1行和3行标签在水平位置对齐)。要解决这个问题,添加:

CGRect currentFrame = myLabel.frame;
CGSize max = CGSizeMake(myLabel.frame.size.width, 500);
CGSize expected = [myString sizeWithFont:myLabel.font constrainedToSize:max lineBreakMode:myLabel.lineBreakMode]; 
currentFrame.size.height = expected.height;
myLabel.frame = currentFrame;
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
[textLabel sizeToFit];
textLabel.numberOfLines = 0;
textLabel.text = @"Your String...";
myUILabel.numberOfLines = 0;
myUILabel.text = @"your long string here";
[myUILabel sizeToFit];