1. Automatically change label width and height
1- (void) CreateLabel12 {3UILabel * label =[[UILabel alloc] initwithframe:cgrectzero];4Label.backgroundcolor =[Uicolor Redcolor];5NSString * str =@"automatically change label width and height";6Label.text =str;7 //This sentence must be put in the back of the padding string8 [Label SizeToFit];9 [Self.view Addsubview:label];Ten}
2. According to the text information to obtain
1- (void) Createlabel2 {3UILabel * label =[[UILabel alloc] initwithframe:cgrectzero];4Label.backgroundcolor =[Uicolor Redcolor];5Label.font = [Uifont systemfontofsize:30.0f];6NSString * str =@"Calculating the width and height of text";7 8Nsdictionary * attributes = @{nsfontattributename: [Uifont systemfontofsize:30.0f]};9 Ten //Calculate the width and height of text one: OneCgsize textSize =[str sizewithattributes:attributes]; A - //Calculate the width and height of text two: - //cgsize textSize = [str boundingrectwithsize:cgsizemake (Maxfloat, maxfloat) options: Nsstringdrawingtruncateslastvisibleline attributes:attributes context:nil].size; the - //reset the label's frame value based on the computed text width height -[Label Setframe:cgrectmake (0, -, Textsize.width, Textsize.height)]; - +Label.text =str; - [Label SizeToFit]; + [Self.view Addsubview:label]; A}
3. Self-adapting with masonry layout
1- (void) CreateLabel22 {3UILabel * Label =[uilabelNew];4Label.backgroundcolor =[Uicolor Orangecolor];5NSString * str =@"It 's easy to use a third-party masonry layout .";6Label.textcolor =[Uicolor Graycolor];7Label.text =str;8 9 //I don't even have to write this .Ten //[Label SizeToFit]; One A [Self.view Addsubview:label]; - - //use masonry to constrain the label or button. Do not set the label or the width of the button, it will calculate its own. the[Label mas_makeconstraints:^ (Masconstraintmaker *Make ) { - -Make.left.equalTo (Self.view.mas_left). With.offset (Ten); -Make.top.equalTo (self.view.mas_top). With.offset ( -); + }]; -}
Had to sigh again masonry!
ios-Text Self-adapting