IOS let the title wrap on the button display

Source: Internet
Author: User

The project encountered the need to let the text line display on the button, and wrote this blog.

1. If the text on the button is fixed, the form is written dead, you can consider the title text plus \ n line break to achieve the effect, but, remember to set this property, otherwise it will not be wrapped,

Button.titleLabel.lineBreakMode = nslinebreakbywordwrapping;

NSString * titlestr = @ "line break \ n Display";

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

This shows the effect:

2. If the text on your button is dynamic, and you want him to wrap to a boundary value, you can use the following method.

First calculate the title text at the specified maximum width of the size value, and then according to his set button width and height line, the code is as follows:

NSString * titlestr = @ "wrap-line display wrap-line display wrap-line display wrap-line display wrap-wrap display line break";

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 (+) options: Nsstringdrawinguseslinefragmentorigin Attributes:@{nsfontattributename:[uifont SystemFontOfSize:13]} Context:nil] ;

Button.frame = CGRectMake (labeltitlesize.size.width+10, labeltitlesize.size.height+10);

[Self.view Addsubview:button];

This shows the effect:

IOS let the title wrap on the button display

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.