iOS 讓按鈕上的標題換行顯示


項目中遇到了要讓按鈕上的文字換行顯示的需求,就寫了這個博客。

1.如果按鈕上的文字固定,形式是寫死的,可以考慮給標題文字加\n換行符來達到效果,但是,記得一定要設置這個屬性,不然是不會換行的,

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;

  NSString * titleStr = @"換行\n顯示";

    UIButton * button = [UIButton new];

    button.backgroundColor = [UIColor orangeColor];

    button.frame = CGRectMake(100, 100, 60, 40);

    button.titleLabel.font = [UIFont systemFontOfSize:13];

    button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;

    [button setTitle:titleStr forState:UIControlStateNormal];

    [self.view addSubview:button];

這樣的顯示效果是這樣的:

2.如果你按鈕上的文字是動態的,想讓他到達一個邊界值后自動換行,可以使用下面的方法。

先計算出標題文字在規定的最大寬度的size值,然后根據他設置按鈕的寬和高就行了,代碼如下:

 NSString * titleStr = @"換行顯示換行顯示換行顯示換行顯示換行顯示換行顯示換行";

    UIButton * button = [UIButton new];

    button.backgroundColor = [UIColor orangeColor];

    button.titleLabel.font = [UIFont systemFontOfSize:13];

    button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;

    [button setTitle:titleStr forState:UIControlStateNormal];

    CGRect labelTitleSize = [titleStr boundingRectWithSize:CGSizeMake(100, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil];

    button.frame = CGRectMake(100, 100, labelTitleSize.size.width+10, labelTitleSize.size.height+10);

   [self.view addSubview:button];

這樣的顯示效果是這樣的:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM