自动调整字体文本框
2016-02-17 本文已影响297人
jiangamh
在指定大小的文本框中显示文本,当不断增加文本数量时,文本框大小不够大时候,需要自动调整字体的大小适应文本框大小,自定义控件AXAutoSuitLabel实现这个功能。
AXAutoSuitLabel头文件如下:
#import <UIKit/UIKit.h>
@interface AXAutoSuitLabel : UILabel
+(AXAutoSuitLabel*)autoSuitLabel;
@end
AXAutoSuitLabel源文件:
#import "AXAutoSuitLabel.h"
#import "UIFont+FontSize.h"
#define MinFontSize 10
@implementation AXAutoSuitLabel
+(AXAutoSuitLabel*)autoSuitLabel
{
return [[self alloc] init];
}
-(void)awakeFromNib
{
self.textAlignment = NSTextAlignmentCenter;
self.numberOfLines = 0;
}
-(id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
self.textAlignment = NSTextAlignmentCenter;
self.numberOfLines = 0;
}
return self;
}
-(void)setText:(NSString *)text
{
BOOL isSesseed = [self reSetFontWithText:text];
if(isSesseed)
{
[super setText:text];
}
}
reSetFontWithText代码如下:
-(BOOL)reSetFontWithText:(NSString*)text
{
UIFont *currentFont = self.font;
CGFloat width = [text boundingRectWithSize:CGSizeMake(999999999, 21) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:currentFont} context:nil].size.width;
//计算的宽度大于当前控件的宽度
if (width > self.bounds.size.width) {
width = self.bounds.size.width;
CGFloat height = [text boundingRectWithSize:CGSizeMake(width, 9999999) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:currentFont} context:nil].size.height;
//如果计算的高度也大于当前控件的高度,重新调整字体
BOOL reSetSesseed = NO;
if (height > self.bounds.size.height)
{
CGFloat fontSize = [currentFont fontSize];
for (int i = fontSize - 1; i >= MinFontSize; i--)
{
height = [text boundingRectWithSize:CGSizeMake(width, 9999999) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:i]} context:nil].size.height;
if (height <= self.bounds.size.height) {
[self setFont:[UIFont systemFontOfSize:i]];
reSetSesseed = YES;
break;
}
}
if (!reSetSesseed) {
return NO;
}
}
}
else
{
//可容纳下,不用调整字体大小
return YES;
}
return YES;
}
[currentFont fontSize]获取字体的字体大小,通过UIFont好像没有现成方法获取字体大小,所以实现了UIFont分类方法实现获取字体大小。分类如下:
#import <UIKit/UIKit.h>
@interface UIFont (FontSize)
//返回-1表示获取失败
-(CGFloat)fontSize;
@end
具体实现:
//返回-1表示获取失败
-(CGFloat)fontSize
{
NSString *des = [self description];
NSArray *desArr = [des componentsSeparatedByString:@";"];
NSString *key = @"font-size";
NSString *desStr = nil;
for (NSString *str in desArr) {
if ([str containsString:key]) {
desStr = str;
break;
}
}
if (desStr) {
NSArray *desStrArr = [desStr componentsSeparatedByString:@" "];
desStr = nil;
for (NSString *str in desStrArr) {
if ([str containsString:@"."]) {
desStr = str;
break;
}
}
if (desStr) {
NSInteger len = [desStr length];
if (len > 2) {
desStr = [desStr substringToIndex:len - 2];
return [desStr floatValue];
}
else
{
return -1;
}
}
}
return -1;
}
通过输出UIFont的description信息,发现description信息中包含了字体大小,所以通过该信息获取UIFont对应字体的大小。
运行结果如下:
当不断输入文本时候,文本框大小不够,自动调小字体以适应文本框大小,文本增加时候结果如下:
屏幕快照 2.pnggithub Demo:https://github.com/jiangtaidi/AXAutoSuitLabel.git