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


当前回答

这段代码根据文本返回大小和高度

+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font
 {
    CGFloat result = font.pointSize+4;
    if (text) 
{
        CGSize size;

        CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, 999)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:@{NSFontAttributeName:font}
                                          context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height+1);
        result = MAX(size.height, result); //At least one row
    }
    return result;
}

其他回答

如果你必须使用:

myLabel.numberOfLines = 0;

属性,也可以在代码中使用标准换行符(“\n”)强制换行。

方法1:

extension UILabel {//Write this extension after close brackets of your class
    func lblFunction() {
        numberOfLines = 0
        lineBreakMode = .byWordWrapping//If you want word wraping
        //OR
        lineBreakMode = .byCharWrapping//If you want character wraping
    }
}

现在像这样简单地调用

myLbl.lblFunction()//Replace your label name 

EX:

Import UIKit

class MyClassName: UIViewController {//For example this is your class. 

    override func viewDidLoad() {
    super.viewDidLoad()

        myLbl.lblFunction()//Replace your label name 

    }

}//After close of your class write this extension.

extension UILabel {//Write this extension after close brackets of your class
    func lblFunction() {
        numberOfLines = 0
        lineBreakMode = .byWordWrapping//If you want word wraping
        //OR
        lineBreakMode = .byCharWrapping//If you want character wraping
    }
}

方法2:

以编程方式

yourLabel.numberOfLines = 0
yourLabel.lineBreakMode = .byWordWrapping//If you want word wraping
//OR
yourLabel.lineBreakMode = .byCharWrapping//If you want character wraping

方法3:

故事板

若要显示多行,请设置0(Zero),这将在标签中显示多行。

如果要显示n行,请设置n。

请看下面的屏幕。

如果要设置标签的最小字体大小,请单击“自动收缩”并选择“最小字体大小”选项

请看下面的屏幕

这里设置最小字体大小

例:9(在这张图中)

如果你的标签得到更多的文本在那个时候,你的标签文本将缩小到9

UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
[labelName sizeToFit];
labelName.numberOfLines = 0;
labelName.text = @"Your String...";
[self.view addSubview:labelName];

使用故事板:选择标签设置行数为零......或者参考这个

myUILabel.numberOfLines = 0;
myUILabel.text = @"your long string here";
[myUILabel sizeToFit];