设为首页 加入收藏

TOP

【IOS】将字体大小不同的文字底部对齐(二)
2017-10-13 10:33:14 】 浏览:7936
Tags:IOS 字体 大小 不同 文字 底部
           100

rc(text)                1.000000,2.333333        105.666667,61.000000          208.666667,120.666667

bounds(label)      1.000000,2.193359        105.541992,60.667969          208.349609,120.335938

相差                                    0,0.139974             0.124675,0.332031                0.317058, 0.330729

rc居然还要比bounds大那么一点点,我认为为了文字不被截取,文字大小还是比其文字边框还要小的,

并且针对不同大小的UIFont或字体类型,这种小的程度还是不一样的。

所以就算设置verticalAlignment属性也发现不了什么区别。

如果只将文字大小设置更大,导致rc比bounds大,那么文字部分就可能会被截取;

如果只增加UILabel的大小,导致rc比bounds小,那么就会看到除了文字外多余的空白区域;

对于后两者,设置verticalAlignment属性,就能够明显的看到上下偏移了。

所以这种方案对于实现所需效果无效。

 

终点: 

找呀找呀  又找到了另外一种方法,可以通过attributedText属性让UILabel显示富文本

实现一个字符串中包含不同颜色、字号等。

我封装了一个方法:

// 获取带有不同样式的文字内容
//stringArray 字符串数组
//attributeAttay 样式数组
- (NSAttributedString *)attributedText:(NSArray*)stringArray attributeAttay:(NSArray *)attributeAttay{
  // 定义要显示的文字内容
    NSString * string = [stringArray componentsJoinedByString:@""];  //拼接传入的字符串数组   // 通过要显示的文字内容来创建一个带属性样式的字符串对象
    NSMutableAttributedString * result = [[NSMutableAttributedString alloc] initWithString:string];
        for(NSInteger i = 0; i < stringArray.count; i++){
     // 将某一范围内的字符串设置样式 [result setAttributes:attributeAttay[i] range:[
string rangeOfString:stringArray[i]]]; } // 返回已经设置好了的带有样式的文字 return [[NSAttributedString alloc] initWithAttributedString:result]; }

 以及其使用

   NSDictionary *attributesExtra = @{NSFontAttributeName:kLabelFont,//字号12
                                              NSForegroundColorAttributeName: [UIColor orangeColor]};
  NSDictionary *attributesPrice = @{NSFontAttributeName:kPriceFont,//字号18
                                               NSForegroundColorAttributeName: [UIColor orangeColor]};
  NSAttributedString *attributedString = [self attributedText:@[@"", @"1314", @""]
                                                 attributeAttay:@[attributesExtra,attributesPrice,attributesExtra]];
   UILabel *price = [[UILabel alloc]init]; 
  price.attributedText
= attributedString;    CGRect rect = [attributedString boundingRectWithSize:CGSizeMake(self.width / 2, 100) options:NSStringDrawingUsesLineFragme ntOrigin context:nil];  //此方法获取到的是自适应的Rect,而不是CGSize 最大Size值为CGSizeMake(self.width / 2, 100)
price.frame = CGRectMake(0,0,rect.size.width, rect.size.height);

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇OC NSArray 数组 下一篇iOS 网络编程:JSON解析

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目