UILabel自适应宽高,实现内部字体自动改变大小,使内容全部显示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
- (void)setFontSizeThatFits:(UILabel*)label { CGFloat fontSizeThatFits; [label.text sizeWithFont:label.font minFontSize:12.0 //最小字体 actualFontSize:&fontSizeThatFits forWidth:label.bounds.size.width lineBreakMode:NSLineBreakByWordWrapping]; label.font = [label.font fontWithSize:fontSizeThatFits]; } |
1 2 3 |
还有一种方法 label.adjustsFontSizeToFitWidth = YES; 这一句话就可以了 |
adjustsFontSizeToFitWidth 实现原理:
1 2 |
self.label1.text = @"1234567890qwertyuiopasdfghjklzxcvbnm"; self.label1.font = [self adjustsFontSize:self.label1]; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
- (UIFont*)adjustsFontSize:(UILabel*)label{ float curFontSize = label.font.pointSize; UIFont *font = label.font; CGRect rect; rect = [label bounds]; if (rect.size.width == 0.0f || rect.size.height == 0.0f) { return 0; } while (curFontSize > label.minimumScaleFactor && curFontSize > 0.0f) { CGSize size = CGSizeZero; // A single line of text should be clipped if (label.numberOfLines == 1) { size = [label.text sizeWithFont:font constrainedToSize:CGSizeMake(rect.size.width, 0.0f) lineBreakMode:NSLineBreakByClipping]; // size = [label.text boundingRectWithSize:CGSizeMake(rect.size.width, 0.0f) // options:NSStringDrawingUsesFontLeading // attributes:@{NSFontAttributeName: _font} // context:NULL].size; } else { //Multiple lines of text should be wrapped size = [label.text sizeWithFont:font constrainedToSize:CGSizeMake(rect.size.width, 0.0f) lineBreakMode:NSLineBreakByWordWrapping]; } if (size.width < rect.size.width && size.height <= rect.size.height) { break; } curFontSize -= 1.0f; font = [font fontWithSize:curFontSize]; } if (curFontSize < label.minimumScaleFactor) { curFontSize = label.minimumScaleFactor; } if (curFontSize < 0.0f) { curFontSize = 1.0f; } font = [font fontWithSize:curFontSize]; return font; } |
转载请注明:天狐博客 » UILabel固定尺寸, 自适应字体大小