Multiple lines of text in UILabel

2019-01-01 16:57发布

Is there a way to have multiple lines of text in UILabel like in the UITextView or should I use the second one instead?

25条回答
余生请多指教
2楼-- · 2019-01-01 17:21

On C#, this worked for me inside UITableViewCell.

        UILabel myLabel = new UILabel();
        myLabel.Font = UIFont.SystemFontOfSize(16);
        myLabel.Lines = 0;
        myLabel.TextAlignment = UITextAlignment.Left;
        myLabel.LineBreakMode = UILineBreakMode.WordWrap;
        myLabel.MinimumScaleFactor = 1;
        myLabel.AdjustsFontSizeToFitWidth = true;

       myLabel.InvalidateIntrinsicContentSize();
       myLabel.Frame = new CoreGraphics.CGRect(20, mycell.ContentView.Frame.Y + 20, cell.ContentView.Frame.Size.Width - 40, mycell.ContentView.Frame.Size.Height);
       myCell.ContentView.AddSubview(myLabel);

I think the point here is:-

            myLabel.TextAlignment = UITextAlignment.Left;
            myLabel.LineBreakMode = UILineBreakMode.WordWrap;
            myLabel.MinimumScaleFactor = 1;
            myLabel.AdjustsFontSizeToFitWidth = true;
查看更多
余生请多指教
3楼-- · 2019-01-01 17:22
UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
[labelName sizeToFit];
labelName.numberOfLines = 0;
labelName.text = @"Your String...";
[self.view addSubview:labelName];
查看更多
低头抚发
4楼-- · 2019-01-01 17:23

Swift 3
Set number of lines zero for dynamic text information, it will be useful for varying text.

var label = UILabel()
let stringValue = "A label\nwith\nmultiline text."
label.text = stringValue
label.numberOfLines = 0
label.lineBreakMode = .byTruncatingTail // or .byWrappingWord
label.minimumScaleFactor = 0.8 . // It is not required but nice to have a minimum scale factor to fit text into label frame

enter image description here

查看更多
几人难应
5楼-- · 2019-01-01 17:26

If you have to use the:

myLabel.numberOfLines = 0;

property you can also use a standard line break ("\n"), in code, to force a new line.

查看更多
后来的你喜欢了谁
6楼-- · 2019-01-01 17:26

lets try this

textLabel.lineBreakMode = NSLineBreakModeWordWrap; // UILineBreakModeWordWrap deprecated     
textLabel.numberOfLines = 0;                          
查看更多
后来的你喜欢了谁
7楼-- · 2019-01-01 17:26

you should try this:

-(CGFloat)dynamicLblHeight:(UILabel *)lbl
{
    CGFloat lblWidth = lbl.frame.size.width;
    CGRect lblTextSize = [lbl.text boundingRectWithSize:CGSizeMake(lblWidth, MAXFLOAT)
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                            attributes:@{NSFontAttributeName:lbl.font}
                                               context:nil];
    return lblTextSize.size.height;
}
查看更多
登录 后发表回答