UILabel实现文本自适应方法(ios7)
- (void)initUserInterface { UILabel *label = [[UILabel alloc]init]; label.numberOfLines = 0; // 须要把显示行数设置成无限制 label.font = [UIFont systemFontOfSize:15]; label.textAlignment = NSTextAlignmentCenter; label.text = @"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; CGSize size = [self sizeWithString:label.text font:label.font]; label.bounds = CGRectMake(0, 0, size.width, size.height); label.center = self.view.center; [self.view addSubview:label]; } // 定义成方法方便多个label调用 添加代码的复用性 - (CGSize)sizeWithString:(NSString *)string font:(UIFont *)font { CGRect rect = [string boundingRectWithSize:CGSizeMake(320, 8000)//限制最大的宽度和高度 options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading |NSStringDrawingUsesLineFragmentOrigin//採用换行模式 attributes:@{NSFontAttributeName: font}//传人的字体字典 context:nil]; return rect.size; }
时间: 2024-11-19 07:04:57