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

來源:互聯網
上載者:User

標籤:line   lstat   ring   src   image   bsp   sys   icon   mode   

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

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];

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

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.