Description
1. Some UIView class extensions are used here
2.sizeWithString This method is not easy to use, only display two lines of text, the other text will not show
3. Do not use with MAS automatic layout otherwise it will cause SizeToFit to not work
4.heightForString This method is capable of achieving an adaptive height
#import "ViewController.h" #define Kheight [[UIScreen Mainscreen] Bounds]size.height
#define KWIDTH [[UIScreen Mainscreen] Bounds].size.width
#import "Uiview+extension.h"
@interface Viewcontroller ()
@end
@implementation Viewcontroller
-(void) Viewdidload {
[Superviewdidload];
NSString *teststring =@ "Do any additional setup after loading the view, typically from a nib. Additional setup after loading the view, typically from a nib. ";
UILabel *label = [[Uilabelalloc] Initwithframe:cgrectmake (30,20, KWidth-30 *, 12)];
Label.text = teststring;
Label.numberoflines = 0;
[Label SizeToFit];
Label.backgroundcolor = [Uicolorlightgraycolor];
[Self.viewaddSubview:label];
UILabel *label2 = [[Uilabelalloc] Initwithframe:cgrectmake (10,cgrectgetmaxy (label.frame), kwidth-10,30)];
Label2.Text = teststring;
Label2.numberoflines = 0;
Label2.size = [selfsizewithstring:label.textfont:[uifontsystemfontofsize:15]];
[Label2 SizeToFit];
Label2.backgroundcolor = [Uicolororangecolor];
[Self.viewaddSubview:label2];
UILabel *label3 = [[Uilabelalloc] Initwithframe:cgrectmake (10,cgrectgetmaxy (label2.frame), kwidth-20,30)];
Label3.text = teststring;
Label3.numberoflines = 0;
Label2.size = [self sizeWithString:label.text font:[uifont systemfontofsize:15];
[Label3 SizeToFit];
Label3.backgroundcolor = [Uicolorbluecolor];
Label3.height = [viewcontrollerheightforstring:teststring fontsize:14 andwidth:kwidth-20];
[SELF.VIEWADDSUBVIEW:LABEL3];
}
This can be used as a class extension method for NSString
+ (float) heightforstring: (NSString *) value fontSize: (float) fontSize andwidth: (float) width
{
float height = [[nsstringstringwithformat:@ "%@\n", Value]boundingrectwithsize:cgsizemake (Width,cgfloat_max) options : Nsstringdrawinguseslinefragmentorigin | Nsstringdrawingusesfontleading attributes:[nsdictionarydictionarywithobjectsandkeys:[uifontsystemfontofsize: Fontsize],nsfontattributename,nil] Context:nil].size.height;
return height;
}
-(Cgsize) sizewithstring: (NSString *) string font: (Uifont *) font
{
Limit maximum width and height//font dictionary with newline//descendants
return [[nsstringstringwithformat:@ "%@\n", String]boundingrectwithsize:cgsizemake (KWidth-10, Cgfloat_max) options: Nsstringdrawinguseslinefragmentorigin | Nsstringdrawingusesfontleading Attributes:[nsdictionarydictionarywithobjectsandkeys:font,nsfontattributename, Nil] context:nil].size;
CGRect rect = [string Boundingrectwithsize:cgsizemake (Kwidth, Cgfloat_max) opt Ions:nsstringdrawinguseslinefragmentorigin | Nsstringdrawingusesfontleading Attributes:@{nsfontattributename:font}
Context:nil];
//
return rect.size;
}
Description of the drawings: