Recommend a second
test One, only change the NumberOfLines property, the label height is not adaptive (there will be some content in text called ...) NSString*str =@"jgreijgirjeirgjierjgiu4t9eumctuv5 vtmnvghvmc5v5tgh58tc857y"; UILabel*label = [[UILabel alloc]initwithframe:cgrectmake ( -, -, -, -)]; Label.font= [Uifont systemfontofsize: the]; Label.backgroundcolor=[Uicolor Cyancolor]; Label.numberoflines=0; Label.text=str; NSLog (@"label1.frame =%@", Nsstringfromcgrect (label.frame)); [Self.view Addsubview:label]; Test two, if you add the NumberOfLines property and [Label1 SizeToFit] This sentence, the label height will be based on the width you set adaptive, the height of the Fram that you set at the beginning will be invalid,,, Note: In fact, his width and your settings also have a certain deviation UILabel*label1 = [[UILabel alloc]initwithframe:cgrectmake ( -, Max, -,0)]; Label1.font= [Uifont systemfontofsize: the]; Label1.backgroundcolor=[Uicolor Cyancolor]; Label1.numberoflines=0; Label1.Text=str; [Label1 SizeToFit]; NSLog (@"label1.frame =%@", Nsstringfromcgrect (label1.frame)); [Self.view Addsubview:label1]; Test Three: Use the method in the class (category) that the teacher encapsulates (autolayoutContent:origin:FontFloat:contentWidth:) without setting the NumberOfLines property and [Label1 SizeToFit] method, but set the Contentwidth: Width and true are a bit biased UILabel*label2 = [[UILabel alloc]initwithframe:cgrectmake ( -, -, -,0)]; //Label2.font = [Uifont systemfontofsize:15];Label2.backgroundcolor =[Uicolor Bluecolor]; Label2.Text=str; [Label2 autolayoutcontent:str Origin:cgpointmake ( -, -) Fontfloat: -Contentwidth: Max]; NSLog (@"label2.frame =%@", Nsstringfromcgrect (label2.frame)); [Self.view Addsubview:label2]; Test four: Label Adaptive height non-mainstream method (used to NumberOfLines and Sizethatfits: method), Advantages: Precision width UILabel*LABEL3 = [[UILabel alloc]initwithframe:cgrectmake ( Max, -, Max,0)]; Label3.font= [Uifont systemfontofsize: the]; Label3.backgroundcolor=[Uicolor Yellowcolor]; Label3.numberoflines=0; Label3.text=str; //label3.linebreakmode = nslinebreakbywordwrapping;//(default)Cgsize size =[Label3 sizethatfits:cgsizemake (Label3.frame.size.width, maxfloat)]; Label3.frame=CGRectMake (label3.frame.origin.x, LABEL3.FRAME.ORIGIN.Y, Label3.frame.size.width, size.height); NSLog (@"label3.frame =%@", Nsstringfromcgrect (label3.frame)); [Self.view Addsubview:label3];
IOS Label Self-adapting height