簡體   English   中英

UILabel 中的多行文本

[英]Multiple lines of text in UILabel

有沒有辦法像UITextView一樣在UILabel有多行文本,還是應該使用第二行?

我找到了解決方案。

只需添加以下代碼即可:

// Swift
textLabel.lineBreakMode = .ByWordWrapping // or NSLineBreakMode.ByWordWrapping
textLabel.numberOfLines = 0 

// For Swift >= 3
textLabel.lineBreakMode = .byWordWrapping // notice the 'b' instead of 'B'
textLabel.numberOfLines = 0

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

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

恢復了舊答案(供參考和願意在6.0以下支持iOS的開發人員使用):

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

從側面看:兩個枚舉值都將變為0

在IB中,將行數設置為0(允許無限行)

使用IB在文本字段中鍵入內容時,請使用“ alt-return”插入一個返回符並轉到下一行(或者您可以復制已經由行分隔的文本)。

我發現的最佳解決方案(對於應該在框架中解決的令人沮喪的問題)類似於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.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;

迅速:

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

如果必須使用:

myLabel.numberOfLines = 0;

屬性,您還可以在代碼中使用標准換行符("\\n")強制換行。

您可以使用\\r轉到下一行,同時使用NSString填充UILabel

UILabel * label;


label.text = [NSString stringWithFormat:@"%@ \r %@",@"first line",@"seconcd line"];

讓我們嘗試一下

textLabel.lineBreakMode = NSLineBreakModeWordWrap; // UILineBreakModeWordWrap deprecated     
textLabel.numberOfLines = 0;                          
textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;

上面的解決方案不適用於我的情況。 我是這樣的:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // ...

    CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Georgia-Bold" size:18.0] constrainedToSize:CGSizeMake(240.0, 480.0) lineBreakMode:UILineBreakModeWordWrap];
    return size.height + 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        // ...
        cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.font = [UIFont fontWithName:@"Georgia-Bold" size:18.0];
    }

    // ...

    UILabel *textLabel = [cell textLabel];
    CGSize size = [text sizeWithFont:[UIFont fontWithName:@"Georgia-Bold" size:18.0]
                                        constrainedToSize:CGSizeMake(240.0, 480.0)
                                            lineBreakMode:UILineBreakModeWordWrap];

    cell.textLabel.frame = CGRectMake(0, 0, size.width + 20, size.height + 20);

    //...
}

使用Story Borad:選擇標簽以將行數設置為零…… 或參考此

在此處輸入圖片說明

迅捷3
對於動態文本信息,將行數設置為零,這對於更改文本很有用。

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

在此處輸入圖片說明

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中對我不起作用,不確定原因。 嘗試使用帶屬性文本和不帶屬性文本的情況。 有什么建議么。

嘗試使用此:

lblName.numberOfLines = 0;
[lblName sizeToFit];

您應該嘗試這樣:

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

這些東西幫助我

更改UILabel的這些屬性

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

在輸入字符串時,請使用\\ n在不同的行中顯示不同的單詞。

范例:

 NSString *message = @"This \n is \n a demo \n message for \n stackoverflow" ;
UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
[labelName sizeToFit];
labelName.numberOfLines = 0;
labelName.text = @"Your String...";
[self.view addSubview:labelName];

您也可以通過情節提要進行此操作:

  1. 在視圖控制器上選擇標簽
  2. 在“屬性”檢查器中,增加“線”選項的值(按Alt + Cmd + 4以顯示“屬性”檢查器)
  3. 雙擊視圖控制器中的標簽,然后編寫或粘貼您的文本
  4. 調整標簽大小和/或增加字體大小,以便可以顯示整個文本

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

例如:

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(零),這將在標簽中顯示多行。

如果要顯示n行,請設置n。

請參閱以下屏幕。

在此處輸入圖片說明

如果要設置標簽的最小字體大小,請單擊“自動收縮”,然后選擇“最小字體大小”選項

請參閱以下屏幕

在此處輸入圖片說明

此處設置最小字體

EX:9(在此圖像中)

如果您的標簽當時有更多文字,您的標簽文字將縮小到9

在此處輸入圖片說明

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

已回答,但您也可以在情節提要中手動進行。 在“標簽的屬性檢查器”下,可以將“換行符”更改為“自動換行”(或“自動換行”)。

在此函數中,您要在標簽中分配的傳遞字符串並通過字體大小代替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;

}

在代碼或情節提要中設置以下內容

Label.lineBreakMode = NSLineBreakByWordWrapping; Label.numberOfLines = 0;

並且請不要忘記為標簽設置左,右,頂部和底部約束,否則它將無法正常工作。

斯威夫特4:

label.lineBreakMode = .byWordWrapping

label.numberOfLines = 0

label.translatesAutoresizingMaskIntoConstraints = false

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

在C#上,這在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);

我認為這里的重點是:

            myLabel.TextAlignment = UITextAlignment.Left;
            myLabel.LineBreakMode = UILineBreakMode.WordWrap;
            myLabel.MinimumScaleFactor = 1;
            myLabel.AdjustsFontSizeToFitWidth = true;

哦,在 2021 年,我被標簽文本困住了 1 小時無法換行,然后意識到我忘記設置標簽的寬度 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)
    ])
}

該代碼根據文本返回大小高度

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM