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


当前回答

UILabel *helpLabel = [[UILabel alloc] init];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:label];
helpLabel.attributedText = attrString;
// helpLabel.text = label;

helpLabel.textAlignment = NSTextAlignmentCenter;
helpLabel.lineBreakMode = NSLineBreakByWordWrapping;
helpLabel.numberOfLines = 0;

出于某些原因,它在iOS 6中不为我工作,不知道为什么。尝试了带和不带带属性的文本。任何建议。

其他回答

已经回答了,但你也可以在故事板中手动执行。在标签的属性检查器下,可以将换行符更改为换行(或字符换行)。

方法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

斯威夫特4:

label.lineBreakMode = .byWordWrapping

label.numberOfLines = 0

label.translatesAutoresizingMaskIntoConstraints = false

label.preferredMaxLayoutWidth = superview.bounds.size.width - 10 

你也可以通过Storyboard来实现:

选择视图控制器上的Label 在属性检查器中,增加Line选项的值(按Alt+Cmd+4显示属性检查器) 双击视图控制器中的Label并写入或粘贴文本 调整标签大小和/或增加字体大小,以便显示整个文本

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

+ (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;
}