Label auto-adaptive height based on the number of characters displayed
Label adaptive height based on the number of characters displayed
1 UILabel * label = [[UILabel alloc] init]; 2 NSString * string = @ "In fact, after years of past, why didn't everyone go through this imaginary journey? Cry in the real smile, smile in the real cry, smoke and rain, half-curtain, dream, many times, we have to admit: Life is not lonely, just don't want to say. \ N listen to all the dust in silence, gradually understand: life, there will always be a lot of helplessness, Hope, disappointment, Hope, sorrow, sorrow, bitter, sweet; pain over, to be strong; to grow after being stupid. \ N there are always some embarrassing gaps in your life. Some people care about you, but you cannot keep them together. Some things envy you, but you cannot possess them. Some miss, it makes you miss, but you regret it for the rest of your life. \ N In this noisy dust, we need to have a suitable place for ourselves to put our souls. \ N may be a quiet homestead; maybe it is a text-free book; maybe it is a maze. As long as it is your own heart, it is the station, in order to start in the future, not so confused. \ N red dust three thousand feet, read in the middle. Life is not always smooth sailing. Because of love, let go; because let go, so silence; because of understanding, so with peace of mind a look back. \ N may be a windy and rainy day that carries the heavy life. It is more suitable for quiet understanding. "; 3 // calculated character if the display width is the same as the label width, it requires a height of 4 CGRect r = [string boundingRectWithSize: CGSizeMake (,) options :( NSStringDrawingUsesLineFragmentOrigin) attributes: @ {NSFontAttributeName: [UIFont systemFontOfSize: 17.f]} context: nil]; 5 label. frame = CGRectMake (30, 30,300, r. size. height); 6 label. text = string; 7 label. numberOfLines = 0; 8 label. backgroundColor = [UIColor cyanColor]; 9 [self. view addSubview: label];
Set the label height to the character to calculate the required height.
Display Effect: (Blue is the background color of the label .)