In the actual code application, we often need to calculate the width and height of a particular text. Then, depending on the length and width values, the container is dynamically set (for example:UILabel) to accommodate the length and width of the
If: We have the following paragraph of text.
uifont *thefont = [uifontsystemfontofsize:];
NSString *strtext = @ " This is a long string, we will calculate the actual required width and height according to the required font size! " ;
1. Calculate the width of the text
Nsmutabledictionary *dic = [nsmutabledictionary dictionarywithobject:[uifont systemfontofsize:14] ForKey: Nsfontattributename]; Cgsize size = [StrText boundingrectwithsize:cgsizemake (maxfloat, 0.0) options:nsstringdrawinguseslinefragmentorigin Attributes:dic context:nil].size;
2. Calculate the height of the text
In this way, the size of the container can be controlled by using the Boundingrectwithsize: method to obtain the length and width.
AboutNslinebreakmodeEnumeration type, as shown below, has been made very clear, will not repeat.
typedef Ns_enum (Nsinteger, Nslinebreakmode) {
nslinebreakbywordwrappin g =0,
nslinebreakbycharwrappinG,
nslinebreakbyclipping,
nslinebreakbytruncatinghead,
nslinebreakbytruncatingtail,
nslinebreakbytruncatingmiddle
}Ns_enum_available_ios(6_0);
[IOS Development] nsstring-Calculating the width and height of text