一:UILabel中字体有多种颜色
UILabel *label = [[UILabel alloc] init]; label.frame = CGRectMake(20, 350, 200, 100); label.backgroundColor = [UIColor yellowColor]; NSString *name = @"David贾永强"; float money = 2.0; NSString *contentStr = [NSString stringWithFormat:@"%@ 五分钟前薅取 %.2f元 羊毛",name,money]; NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:contentStr]; [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, contentStr.length)]; //名字 NSRange nameRang = NSMakeRange(0, name.length); [str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:nameRang]; [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:nameRang]; //钱数 NSRange moneyRang = NSMakeRange(name.length + 7, 6); [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:moneyRang]; [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:moneyRang]; label.attributedText = str; [label sizeToFit]; [self.view addSubview:label];
效果图:
二:字符串自动计算高度/换行 方法一:
//进行动态获取高度和宽度。必须用这个NSDictionary,不能用NSMutableDictionary这个。 NSString *str = @"自动计算高度,然后换行,自动计算高度,然后换行,自动计算高度,然后换行,自动计算高度,然后换行,自动计算高度,然后换行,自动计算高度,然后换行,自动计算高度,然后换行,自动计算高度,然后换行,自动计算高度,然后换行,结束"; UIFont *font = [UIFont systemFontOfSize:15.0f]; NSDictionary *attributes = @{ NSFontAttributeName: font }; CGSize size = [str sizeWithAttributes:attributes]; UILabel *label = [[UILabel alloc] init]; label.frame = CGRectMake(10, 100, size.width, size.height); label.text = str; label.font = font; label.backgroundColor = [UIColor orangeColor]; [self.view addSubview:label]; // 自动计算高度,然后换行 label.lineBreakMode = NSLineBreakByWordWrapping; label.numberOfLines = 0; //boundSize,决定label的宽度. 设为屏幕宽度-100. 也可以设置固定的宽度 CGSize boundSize = CGSizeMake([UIScreen mainScreen].bounds.size.width-100, MAXFLOAT); CGSize brSize = [str boundingRectWithSize:boundSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size; label.frame = CGRectMake(20, 200, brSize.width, brSize.height);
效果图:
字符串自动计算高度/换行 方法二:
//UILabel 的高度会根据字体自身,大小,label的宽度 自动计算. UILabel *_label = [[UILabel alloc] initWithFrame:CGRectMake(20, 150, 300, 0)]; _label.backgroundColor = [UIColor greenColor]; _label.font = [UIFont systemFontOfSize:20]; _label.text = @"自动计算高度,然后换行自动计算高度,然后换行,自动计算高度,然后换行自动计算高度,然后换行,结束"; _label.numberOfLines = 0; [_label sizeToFit]; [self.view addSubview:_label];