UILabel adaptive

UILabel wrap
UILabel * examp_LB = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, 150)]; Examp_lb. backgroundColor = [UIColor colorWithRed:1 green:1 blue:0 alpha:0.3f]; // Examp_lb.text = "examp_lb.text" @"abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghij klmnopqrstuvwxyz"; Examp_lb. numberOfLines = 0; / / must be set to 0, will automatically wrap examp_LB. LineBreakMode = NSLineBreakByCharWrapping; [self.view addSubview:examp_LB];Copy the code

NSLineBreakMode enumeration:

// NSParagraphStyle typedef NS_ENUM(NSInteger, NSLineBreakMode) { NSLineBreakByWordWrapping = 0, // Wrap at word boundaries, default NSLineBreakByCharWrapping, // Wrap at character boundaries NSLineBreakByClipping, // Simply clip NSLineBreakByTruncatingHead, // Truncate at head of line: "... wxyz" NSLineBreakByTruncatingTail, // Truncate at tail of line: "abcd..." NSLineBreakByTruncatingMiddle // Truncate middle of line: "ab... yz" } NS_ENUM_AVAILABLE(10_0, 6_0);Copy the code

Several UILabel height corresponding effects:

UILabel * examp_LB = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, 50)];
Copy the code

Effect: Can’t fit (can’t finish)

UILabel * examp_LB = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, 100)];
Copy the code

Effect: Loading, leaving a little space

UILabel * examp_LB = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, 150)];
Copy the code

Effect: Loaded, a lot of space

Disadvantages: you must ensure that the height set by UILabel is completely higher than the height of the font **. Otherwise it won’t fit!

UILabel width adaptive

When using width adaptive, it is common to center the string (for the sake of beauty 😂😂) : Set “textAlignment” to “NSTextAlignmentCenter” example:

UILabel * examp_LB2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, self.view.frame.size.width, 50)]; Examp_lb2. backgroundColor = [UIColor colorWithRed:1 green:0 blue:1 alpha:0.2f]; examp_LB2.text = @"abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghij klmnopqrstuvwxyz"; examp_LB2.adjustsFontSizeToFitWidth = YES; // Adaptive width [self.view addSubview:examp_LB2];Copy the code

Effect: The string is displayed in full


The effect of “changing the length of a string after reducing its length” :

examp_LB2.text = @"abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcde";
Copy the code

Effect: String length reduced

examp_LB2.text = @"abcdefghijk";
Copy the code

Effect: The string length is too short to fully fill the length of the Label


Change the width of the UILabel

UILabel * examp_LB3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 260, 150, 50)]; Examp_lb3. backgroundColor = [UIColor colorWithRed:1 green:0 blue:1 alpha:0.2f]; examp_lb3. backgroundColor = [UIColor colorWithRed:1 green:0 blue:1 alpha:0.2f]; examp_LB3.text = @"abcdefghijk"; examp_LB3.textAlignment = NSTextAlignmentCenter; . / / the writing center examp_LB3 adjustsFontSizeToFitWidth = YES; // Adaptive width [self.view addSubview:examp_LB3];Copy the code

Effect: Finished loading

UILabel * examp_LB3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 260, 100, 50)];
Copy the code

Effect: Slightly blank

UILabel * examp_LB3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 260, 150, 50)];
Copy the code

Effect: Lots of white space


UILabel Newline, adaptive width
UILabel * examp_LB4 = [[UILabel alloc] initWithFrame:CGRectMake(0, 320, self.view.frame.size.width, 50)]; Examp_LB4. BackgroundColor = [UIColor colorWithRed:1 green:0 blue:1 alpha:0.2f]; examp_LB4.text = @"abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghij klmnopqrstuvwxyz"; examp_LB4.numberOfLines = 0; / / the number of rows is set to 0 examp_LB4. AdjustsFontSizeToFitWidth = YES; [self.view addSubview:examp_LB4];Copy the code

⚠️ : cannot set the property of its newline mode!!!!! Or “adjustsFontSizeToFitWidth” setting will become invalid!

UILabel * examp_LB5 = [[UILabel alloc] initWithFrame:CGRectMake(0, 380, self.view.frame.size.width, 50)]; Examp_LB5. BackgroundColor = [UIColor colorWithRed:1 green:0 blue:1 alpha:0.2f]; examp_LB5.text = @"abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghij klmnopqrstuvwxyz"; examp_LB5.numberOfLines = 0; examp_LB5.lineBreakMode = NSLineBreakByCharWrapping; / / (❌ ❌ ❌ ❌ ❌ ❌) / / due to set up a newline mode, adaptive width becomes inactive examp_LB5. AdjustsFontSizeToFitWidth = YES; [self.view addSubview:examp_LB5];Copy the code

Effect:

UILabel ⭐️ fully adaptive ⭐️

Use the following methods:

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);
Copy the code

To record the frame of the UILabel, read it out (return type: CGRect) and use its frame!

After overwriting the method in the class used, it looks like this:

// Pass in text, font and maximum size, - (CGSize)sizeWithText:(NSString *)text andFont:(UIFont *)font maxSize:(CGSize)maxSize {NSDictionary *attrs = @{NSFontAttributeName : font}; return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size; } // Pass in text, font, and maximum width, -(CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxW:(CGFloat)maxW {NSMutableDictionary *attrs=[NSMutableDictionary dictionary]; attrs[NSFontAttributeName]=font; CGSize maxSize=CGSizeMake(maxW, MAXFLOAT); return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size; } // Pass in text, font (default: - (CGSize)sizeWithText:(NSString *)text FONT :(UIFont *)font {return [self sizeWithText:text font:font maxW:MAXFLOAT]; }Copy the code

Inside “viewDidLoad {}” :

UILabel * examp_LB6 = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, 50)]; Examp_LB6. BackgroundColor = [UIColor colorWithRed:1 green:0 blue:1 alpha:0.2f]; Examp_LB6. NumberOfLines = 0; examp_LB6.lineBreakMode = NSLineBreakByCharWrapping; [self.view addSubview:examp_LB6]; // Set the required string for adaptive NSString * STR = @"abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcdefghij klmnopqrstuvwxyz"; examp_LB6.text = str; UIFont *font = [UIFont fontWithName:@"Arial" size:12]; examp_LB6.font = font;Copy the code

Here are the three methods invoked:

  • 1. Enter text, font and maximum size to get width and height

    // Pass in text, font and maximum size, To get the width and the height CGSize labelsize = [self sizeWithText: STR andFont: the font maxSize: CGSizeMake (self. View. Frame. The size. Width, 100)]. examp_LB6.frame = CGRectMake(examp_LB6.frame.origin.x,examp_LB6.frame.origin.y, labelsize.width, labelsize.height);Copy the code

Effect:

  • 2. Input text, font and maximum width, you can get width and height

    CGSize labelsize = [self sizeWithText: STR font:font maxW:290]; CGSize labelsize = [self sizeWithText: STR font:font maxW:290]; Examp_lb6.frame = CGRectMake(examp_lb6.frame.origin. X, examp_lb6.frame.origin. Y, labelsize.width, examp_lb6.frame. labelsize.height);Copy the code

Effect:

  • 3. Pass text, font (default: maximum width)

    CGSize labelSize = [self sizeWithText: STR font:font]; examp_LB6.frame = CGRectMake(examp_LB6.frame.origin.x,examp_LB6.frame.origin.y, labelsize.width, labelsize.height);Copy the code

Effect: the maximum length of the Label is obtained

It displays the width of the screen. Enter a breakpoint and check the maximum length of the Label:


Of course, using the “Debug View Hierarchy” method of the “View position relationship” of the system is futile, and you cannot see the off-screen View.

Using an app called”Reveal“Software can be viewedOutside the screenThe view:

Reveal Reveal download address: revealapp.com/download/ of course, I use the cracked version ~ 😂😂😂😂😂😂

Reveal—– View size and location relationship viewing and debugging. Reveal usage instructions are widely available online, so I won’t go into details


It can also be used directly

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);
Copy the code

Method returns the “CGRect” structure.

The code is as follows:

NSDictionary *attribute_Dict = @{NSFontAttributeName: font}; / / font dictionary CGRect label_Rect = [STR boundingRectWithSize: CGSizeMake (self. View. Frame. The size, width, 0) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine attributes:attribute_Dict context:nil]; float label_height = label_Rect.size.height; float label_width = label_Rect.size.width; examp_LB6.frame = CGRectMake(examp_LB6.frame.origin.x,examp_LB6.frame.origin.y, label_width, label_height);Copy the code

Effect:

When the string is centered:

examp_LB6.textAlignment = NSTextAlignmentCenter; // The handwriting is in the middleCopy the code

Effect:


The following is an example of changing the length of a string, and you’ll see that the height and width of UILabel are completely adaptive !!!!!

NSString * str = @"abcdefghijklmnopqrstuvwxyz_abcdefghijklmnopqrstuvwxyz_abcde";
Copy the code

Effect:

3. Short enough in length:

NSString * STR = @abcdefghi; NSString * STR = @abcdefghi;Copy the code

Effect: UILabel height and width adaptive

UILabel uses rich text

Text Kit makes it very easy to implement some complex Text styles and layouts, and the core data structure that the Text Kit rich Text framework uses is the NSAttributeString. Text Kit refers to the classes and protocols that UIKit framework uses to provide high quality typography services. It enables programs to store, typeset, and display text information, and supports all the features required for typesetting (including coining, concagination, newline, and alignment).

1. Initialization method

- (instancetype)initWithString:(NSString *)str; - (instancetype)initWithString:(NSString *)str attributes:(nullable NSDictionary<NSString *, id> *)attrs; - (instancetype)initWithAttributedString:(NSAttributedString *)attrStr; // Initialization using NSAttributedString, similar to NSMutableString and NSStringCopy the code

NSMutableAttributedString attribute set:

// setAttributes for a text in a range - (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range; // add an attribute to a text in a range - (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range; // add multiple attributes to a range of text - (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range; // Remove an attribute from a range - (void)removeAttribute (NSString *)name range (NSRange)range;Copy the code

2. Common attributes and descriptions

NSFontAttributeName Specifies the font attribute (font, size). Default: font: Helvetica Neue) size: 12 NSForegroundColorAttributeNam font color, values for UIColor object. The default value is black NSBackgroundColorAttributeName font background color of the area, the values for UIColor object. The default value is nil, the transparent color NSLigatureAttributeName. The value is an NSNumber object (integer). 0 means that there is no concatenation, and 1 means that the character spacing is set using the default concatenation character NSKernAttributeName. Values for NSNumber object (integer), when the spacing widened, negative narrow spacing NSStrikethroughStyleAttributeName delete a line, Values for the NSNumber objects (integer) NSStrikethroughColorAttributeName strikethrough color, values for UIColor object. The default value is black NSUnderlineStyleAttributeName underline, values for NSNumber object (integer), enumerated constants NSUnderlineStyle of values, Similar to strikethrough NSUnderlineColorAttributeName underline color, values for UIColor object. Defaults to black NSStrokeWidthAttributeName set stroke width, as NSNumber object value (integer), negative filling effect, when the effect of hollow NSStrokeColorAttributeName filling part color, not a font color, Values for NSShadowAttributeName UIColor object shadow attributes, values as the object of NSShadow NSTextEffectAttributeName set special effects, text values as nsstrings object, Currently possesses the printing effect only available NSBaselineOffsetAttributeName set baseline offset value, value for NSNumber (float), as on the slant, slope under negative partial NSObliquenessAttributeName set the font, NSNumber (float), positive right, negative left and NSExpansionAttributeName sets the text horizontal stretch property, which is NSNumber (float), positive horizontal stretch text, Negative transverse compression set text NSWritingDirectionAttributeName writing direction, writing written from left to right or from right to left NSVerticalGlyphFormAttributeName set text layout direction, The value is an NSNumber object (integer), where 0 indicates horizontal text, 1 landscape text NSAttachmentAttributeName set attachments, text values as NSTextAttachment object, often used in text images are mixed NSParagraphStyleAttributeName set the text paragraphs typesetting format, The value is an NSParagraphStyle objectCopy the code

NSLinkAttributeName Sets the link attribute and calls the browser to open the specified URLCopy the code

Adding Links to Rich Text: iOS Development — Hyperlinks to rich text

Rich text example demonstrating the various attributes of the site: www.itnose.net/detail/6177…

An 🌰 :
/ / garbage code section UILabel * examp_Attrb_LB1 = [[UILabel alloc] initWithFrame: CGRectMake (0, 50, the self. The frame. The size, width, 50)]; Examp_attrb_lb1. backgroundColor = [UIColor colorWithRed:0.5 green:1 blue:0 alpha:0.2f]; [self.view addSubview:examp_Attrb_LB1]; UILabel * examp_Attrb_LB2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 110, self.view.frame.size.width, 50)]; Examp_attrb_lb2. backgroundColor = [UIColor colorWithRed:0.5 green:1 blue:0 alpha:0.2f]; [self.view addSubview:examp_Attrb_LB2]; UILabel * examp_Attrb_LB3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 170, self.view.frame.size.width, 50)]; Examp_attrb_lb3. backgroundColor = [UIColor colorWithRed:0.5 green:1 blue:0 alpha:0.2f]; [self.view addSubview:examp_Attrb_LB3]; UILabel * examp_Attrb_LB4 = [[UILabel alloc] initWithFrame:CGRectMake(0, 260, self.view.frame.size.width, 50)]; Examp_Attrb_LB4. BackgroundColor = [UIColor colorWithRed:0.5 green:1 blue:0 alpha:0.2f]; [self.view addSubview:examp_Attrb_LB4]; UILabel * examp_Attrb_LB5 = [[UILabel alloc] initWithFrame:CGRectMake(0, 320, self.view.frame.size.width, 50)]; Examp_Attrb_LB5. BackgroundColor = [UIColor colorWithRed:0.5 green:1 blue:0 alpha:0.2f]; [self.view addSubview:examp_Attrb_LB5]; UILabel * examp_Attrb_LB6 = [[UILabel alloc] initWithFrame:CGRectMake(0, 380, self.view.frame.size.width, 150)]; Examp_Attrb_LB6. BackgroundColor = [UIColor colorWithRed:0.5 green:1 blue:0 alpha:0.2f]; [self.view addSubview:examp_Attrb_LB6]; //《《《《《《《《《《《《《 Enter the subject 》》》》》》》》》》》》》 // Rich text string 1 NSAttributedString * attrStr1 = [[NSAttributedString alloc] initWithString:@"abcdefghij"]; NSAttributedString * attrStr2 = [[NSAttributedString alloc] // Almost useless 😂 // immutable rich text 2 (with rich text attribute (attribute of ⭐️ all ⭐️)) initWithString:@"hijklmnopqr" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:30.f],NSForegroundColorAttributeName:RGB(137, 198, 41)}]; // Immutable rich text 3 (⭐️ copies ⭐️ a rich text) NSAttributedString * attrStr3 = [[NSAttributedString alloc] initWithAttributedString:attrStr2]; / / ⭐ ️ copy ⭐ ️ a rich text / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = / / 4 NSMutableAttributedString * attrStr4 variable rich text  = [[NSMutableAttributedString alloc] initWithAttributedString:attrStr2]; / / get the mno string ⭐ ️ region ⭐ ️ NSRange rag_1 = [attrStr4. String localizedStandardRangeOfString: @ "mno"]. / / add "mno" string in the scope of font properties [attrStr4 addAttribute: NSFontAttributeName value: [UIFont systemFontOfSize: 10. F] range: rag_1]; / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = / / variable rich text NSMutableAttributedString * attrStr5 = 5 [[NSMutableAttributedString alloc] initWithString:@"stuvwxyz"]; / / to add or change the properties of the dictionary NSDictionary * attr_Dict = @ {NSForegroundColorAttributeName: [UIColor orangeColor]. NSUnderlineStyleAttributeName: [NSNumber numberWithFloat: 1.0]}; // Font color and underline // ⭐️ Add rich text attribute in ⭐️ [attrStr5 addAttributes:attr_Dict range:NSMakeRange(0, attrstr5.length)]; // The entire string (NSMakeRange(0, AttrStr5. Length)) / / we need to add or change the range of attribute dictionary NSDictionary * attr_Dict2 = @ {NSBackgroundColorAttributeName: [UIColor cyanColor]. NSForegroundColorAttributeName: [UIColor blueColor], NSStrikethroughStyleAttributeName: [NSNumber numberWithFloat: 1.0]}. NSRange rag_2 = NSMakeRange(2, 2); NSRange rag_2 = NSMakeRange(2, 2); // ⭐️ set rich text attributes within ⭐️ [attrStr5 setAttributes:attr_Dict2 range:rag_2]; / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = / / variable rich text NSMutableAttributedString * attrStr6 = 6 [[NSMutableAttributedString alloc] initWithString:@"abcdefghijklmnopqrstuvwxyz"]; // Label for (int I = 0; i < attrStr6.string.length; I + +) {/ / all changes to the attributes of the dictionary NSDictionary * attr_Dict = @ {NSForegroundColorAttributeName: [UIColor colorWithRed:arc4random()%256/255.f green:arc4random()%256/255.f blue:arc4random()%256/255.f alpha:1], NSFontAttributeName:[UIFont systemFontOfSize:(arc4random()%20+30)/1.f] }; NSRange rag = NSMakeRange(I, 1); NSRange rag = NSMakeRange(I, 1); // ⭐️ set rich text attributes in the ⭐️ range [attrStr6 setAttributes:attr_Dict range:rag]; } // add a rich text string to the Label: examp_attrb_lb1.attributedText = attrStr1; examp_Attrb_LB2.attributedText = attrStr2; examp_Attrb_LB3.attributedText = attrStr3; examp_Attrb_LB4.attributedText = attrStr4; examp_Attrb_LB5.attributedText = attrStr5; examp_Attrb_LB6.attributedText = attrStr6;Copy the code

Effect:

Examp_Attrb_LB6 implements a newline:

Examp_Attrb_LB6. NumberOfLines = 0; examp_Attrb_LB6.lineBreakMode = NSLineBreakByCharWrapping;Copy the code

Effect:

Examples of rich text in UITextView, UITextField:

UITextView * tv = [[UITextView alloc] initWithFrame:CGRectMake(9, 20, 100, 200)]; TV. BackgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.2f]; tv.attributedText = attrStr6; [self.view addSubview:tv]; UITextField * tf = [[UITextField alloc] initWithFrame:CGRectMake(10, 260, 200, 20)]; Tf. backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.2f]; tf.attributedText = attrStr6; [self.view addSubview:tf];Copy the code

Effect:

When a string is added after a string, the following rich text copies the font, color, and size of the previous rich text character.


More methods and properties See the apple official documentation: developer.apple.com/library/ios…

Generally, rich text is simply displayed in one or two places and encapsulated in custom controls. Of course, you can add your own category to the UILabel using rich text

(2017.01.19)

goyohol’s essay