iOS文字样式处理总结(字体、前背景色、斜体、加粗、对齐、行间距、段间距、动态获取字符串label宽高等)

iOS 文字样式处理总结(字体、前背景色、斜体、加粗、对齐、行间距、段间距、动态获取字符串label宽高等)

在iOS开发中,常常会有一段文字显示不同的颜色和字体,或者给某几个文字加删除线或下划线的需求。NSMuttableAttstring(带属性的字符串),可以灵活实现以上功能。
NSMutableParagraphStyle段落风格,设置行间距、段间距、缩进、对齐方式等。

1. 实例化方法和使用方法

实例化方法:
使用字符串初始化
- (id)initWithString:(NSString *)str;
//例:
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedStringalloc]initWithString:@"文字样式处理"];
字典中存放一些属性名和属性值:
- (id)initWithString:(NSString *)str attributes:(NSDictionary *)attrs;
//如:
NSDictionary *attributeDict = [NSDictionarydictionaryWithObjectsAndKeys:
                                [UIFontsystemFontOfSize:15.0],NSFontAttributeName,
                                [UIColorredColor],NSForegroundColorAttributeName,
                               NSUnderlineStyleAttributeName,NSUnderlineStyleSingle,nil];
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedStringalloc]initWithString:@"文字样式处理" attributes:attributeDict];
使用NSAttributedString初始化,跟NSMutableString,NSString类似:
- (id)initWithAttributedString:(NSAttributedString *)attester;
使用方法:
为某一范围内文字设置多个属性
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
为某一范围内文字添加某个属性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
为某一范围内文字添加多个属性
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
移除某范围内的某个属性
- (void)removeAttribute:(NSString *)name range:(NSRange)range;

2. 常见的属性及说明

NSFontAttributeName //字体
NSParagraphStyleAttributeName //段落格式
NSForegroundColorAttributeName //字体颜色
NSBackgroundColorAttributeName //背景颜色
NSStrikethroughStyleAttributeName //删除线格式
NSUnderlineStyleAttributeName //下划线格式
NSStrokeColorAttributeName //删除线颜色
NSStrokeWidthAttributeName //删除线宽度
NSShadowAttributeName //阴影


NSParagraphStyleAttributeName

段落的风格(设置首行,行间距,对齐方式什么的)
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];  
paragraphStyle.lineSpacing = 10;// 字体的行间距  
paragraphStyle.firstLineHeadIndent = 20.0f;//首行缩进  
paragraphStyle.alignment = NSTextAlignmentJustified;//(两端对齐的)文本对齐方式:(左,中,右,两端对齐,自然)  
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;//结尾部分的内容以……方式省略 ( "...wxyz" ,"abcd..." ,"ab...yz")  
paragraphStyle.headIndent = 20;//整体缩进(首行除外)  
paragraphStyle.tailIndent = 20;//  
paragraphStyle.minimumLineHeight = 10;//最低行高  
paragraphStyle.maximumLineHeight = 20;//最大行高  
paragraphStyle.paragraphSpacing = 15;//段与段之间的间距  
paragraphStyle.paragraphSpacingBefore = 22.0f;//段首行空白空间/* Distance between the bottom of the previous paragraph (or the end of its paragraphSpacing, if any) and the top of this paragraph. */  
paragraphStyle.baseWritingDirection = NSWritingDirectionLeftToRight;//从左到右的书写方向(一共三种)  
paragraphStyle.lineHeightMultiple = 15;/* Natural line height is multiplied by this factor (if positive) before being constrained by minimum and maximum line height. */  
paragraphStyle.hyphenationFactor = 1;//连字属性 在iOS,唯一支持的值分别为0和1  
两个样式枚举
typedef NS_ENUM(NSInteger, NSLineBreakMode) {/* What to do with long lines */  
    NSLineBreakByWordWrapping = 0,     /* Wrap at word boundaries, default */  
    NSLineBreakByCharWrapping,/* Wrap at character boundaries */  
    NSLineBreakByClipping,/* Simply clip */剪掉后面显示不了的部分  
    NSLineBreakByTruncatingHead,/* Truncate at head of line: "...wxyz" */头部分的内容以……方式省略  
    NSLineBreakByTruncatingTail,/* Truncate at tail of line: "abcd..." */结尾部分的内容以……方式省略  
    NSLineBreakByTruncatingMiddle/* Truncate middle of line:  "ab...yz" */中间部分的内容以……方式省略  
} NS_ENUM_AVAILABLE_IOS(6_0);  


typedef NS_ENUM(NSInteger, NSWritingDirection) {  
    NSWritingDirectionNatural       = -1,    // Determines direction using the Unicode Bidi Algorithm rules P2 and P3  
    NSWritingDirectionLeftToRight   =  0,    // Left to right writing direction 左到右的书写方向  
    NSWritingDirectionRightToLeft   =  1    // Right to left writing direction 右到左的书写方向  
} NS_ENUM_AVAILABLE_IOS(6_0);  
/* 
     NSFontAttributeName 字体大小 
     NSParagraphStyleAttributeName 段落的风格(设置首行,行间距,对齐方式什么的) 
     NSKernAttributeName 字间距 
     */  
    NSDictionary *attributes = @{  
                                 NSFontAttributeName:[UIFont systemFontOfSize:15],  
                                 NSParagraphStyleAttributeName:paragraphStyle,  
                                 NSKernAttributeName:@(10),  

                                 };  
    textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];  

再来个实例

    //随便定义一个字符串,做测试使用
    NSString *massageStr = @"\t北京乌托邦有限公司(以下简称“乌托邦”)在此特别提醒您(用户)在注册成为用户之前,请认真阅读本《用户协议》(以下简称“协议”),确保您充分理解本协议中各条款。请您审慎阅读并选择接受或不接受本协议。除非您接受本协议所有条款,否则您无权注册、登录或使用本协议所涉服务。您的注册、登录、使用等行为将视为对本协议的接受,并同意接受本协议各项条款的约束。\r\n \t本协议约定乌托邦与用户之间关于“乌托邦”软件服务(以下简称“服务”)的权利义务。“用户”是指注册、登录、使用本服务的个人。本协议可由乌托邦随时更新,更新后的协议条款一旦公布即代替原来的协议条款,恕不再另行通知,用户可在本网站查阅最新版协议条款。在乌托邦修改协议条款后,如果用户不接受修改后的条款,请立即停止使用乌托邦提供的服务,用户继续使用乌托邦提供的服务将被视为接受修改后的协议。";


    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:massageStr];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

   [paragraphStyle setLineSpacing:20];//调整行间距

   [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.agreementText length])];

   [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 12)]; // 0为起始位置 length是从起始位置开始 设置指定颜色的长度

   [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(18, 3)];

   //设置尺寸
   [attributedString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(18, 3)]; // 0为起始位置 length是从起始位置开始 设置指定字体尺寸的长度
根据字符串获取宽高
根据宽度求高度 content 计算的内容 width 计算的宽度 font字体大小
+ (CGFloat)getHeightWithContent:(NSString *)content width:(CGFloat)width font:(CGFloat)font{

    CGRect rect = [content boundingRectWithSize:CGSizeMake(width, 999)
                                                           options:NSStringDrawingUsesLineFragmentOrigin
                                                        attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}
                                                           context:nil];
    return rect.size.height;
}
根据高度度求宽度 content 计算的内容 Height 计算的高度 font字体大小

+ (CGFloat)getWidthWithContent:(NSString *)content height:(CGFloat)height font:(CGFloat)font{

    CGRect rect = [content boundingRectWithSize:CGSizeMake(999, height)
                                        options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}
                                        context:nil];
    return rect.size.width;
}

辛苦总结,转载请注明出处,谢谢!

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值