iOS-文字自適應

來源:互聯網
上載者:User

標籤:

 

1.自動改變Label的寬和高

 1 - (void)createLabel1 2 { 3     UILabel * label = [[UILabel alloc] initWithFrame:CGRectZero]; 4     label.backgroundColor = [UIColor redColor]; 5     NSString * str = @"自動改變label的寬和高"; 6     label.text = str; 7     //這句話一定要放填充字串的後面 8     [label sizeToFit]; 9     [self.view addSubview:label];10 }

2.根據文字資訊擷取

 1 - (void)createLabel 2 { 3     UILabel * label = [[UILabel alloc] initWithFrame:CGRectZero]; 4     label.backgroundColor = [UIColor redColor]; 5     label.font = [UIFont systemFontOfSize:30.0f]; 6     NSString * str = @"計算文本的寬和高"; 7      8     NSDictionary * attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:30.0f]}; 9     10     //計算文本的寬高方式一:11     CGSize textSize = [str sizeWithAttributes:attributes];12     13     //計算文本的寬高方式二:14     //CGSize textSize = [str boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;15     16     //根據計算的文本寬高重新設定label的frame值17     [label setFrame:CGRectMake(0, 20, textSize.width, textSize.height)];18     19     label.text = str;20     [label sizeToFit];21     [self.view addSubview:label];22 }

3.用Masonry布局自適應

 1 - (void)createLabel2 2 { 3     UILabel * label =[UILabel new]; 4     label.backgroundColor = [UIColor orangeColor]; 5     NSString * str = @"用第三方的Masonry布局好簡單"; 6     label.textColor = [UIColor grayColor]; 7     label.text = str; 8      9     //甚至這一句都不用寫10     //[label sizeToFit];11     12     [self.view addSubview:label];13     14     //用Masonry去約束label或者button.不設定label或者button的寬高,它會自己計算的。15     [label mas_makeConstraints:^(MASConstraintMaker *make) {16        17         make.left.equalTo(self.view.mas_left).with.offset(10);18         make.top.equalTo(self.view.mas_top).with.offset(100);19     }];20 }

不得不再次感歎Masonry!

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.