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


当前回答

UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
[textLabel sizeToFit];
textLabel.numberOfLines = 0;
textLabel.text = @"Your String...";

其他回答

哦,在2021年,我被一个标签文本困住了,一个小时都不能换行,然后意识到我忘记设置标签的宽度,WTF。

let stepLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.textAlignment = .center
    label.lineBreakMode = .byWordWrapping
    label.numberOfLines = 0
    label.text = "Put your device and computer under same Wi-Fi network."
    
    return label
}()

override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .white
    view.addSubview(stepLabel)

    NSLayoutConstraint.activate([
        stepLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        stepLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        stepLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.7)
    ])
}
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中不为我工作,不知道为什么。尝试了带和不带带属性的文本。任何建议。

设置换行模式为换行,行数为0:

// Swift
textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 0

// Objective-C
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;

// C# (Xamarin.iOS)
textLabel.LineBreakMode = UILineBreakMode.WordWrap;
textLabel.Lines = 0;  

恢复旧答案(供参考和开发者愿意支持iOS 6.0以下):

textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;

另一方面:两个enum值都为0。

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

斯威夫特4:

label.lineBreakMode = .byWordWrapping

label.numberOfLines = 0

label.translatesAutoresizingMaskIntoConstraints = false

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