IOS to achieve automatic acquisition of label height, width and last position

Time:2021-4-12

preface

This paper mainly introduces the relevant content about IOS automatic acquisition of label height, width and the last position, and shares it for your reference. I won’t say much, let’s take a look at the detailed introduction.

1、 Get the width to get the length of the string when it is not folded into a single line


CGSize titleSize = [aString sizeWithFont:font constrainedToSize:CGSizeMake(MAXFLOAT, 30)];

Note:If you want to get the width, the width of size should be set to maxfloat.

2、 Gets the actual height of the string within the specified size (wrap if the width exceeds the width of label)


CGSize titleSize = [aString sizeWithFont:font constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];

Note:If you want to get the height, the height of size should be set to maxfloat.

3、 In actual programming, sometimes it is necessary to calculate the position of the last character of a paragraph of text and add pictures or other controls (such as Info Icon) after it

The following code is the method to calculate the position of the last character in the label.

CGSize sz = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(MAXFLOAT, 40)];

CGSize linesSz = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];

if( sz.width  <=  linesSz.width )// judge whether to break the line

{

lastPoint = CGPointMake(label.frame.origin.x + sz.width, label.frame.origin.y);

}

else

{

lastPoint = CGPointMake(label.frame.origin.x + (int)sz.width % (int)linesSz.width,linesSz.height - sz.height);

}

summary

The above is the whole content of this article, I hope the content of this article has a certain reference value for your study or work, if you have any questions, you can leave a message to exchange, thank you for your support for developer.