Attributed Strings

来源:互联网 发布:2013网络作家富豪榜 编辑:程序博客网 时间:2024/05/16 10:32

属性字符串(Attributed Strings)可以为字符串的每个字符字符设置属性。如颜色,大小,字体样式等。每个字符都有一个属性字典。

NSAttributedString

首先说明的是,NSAttributedString并不是NSString的子类。你可以从NSAttribuedString中获得一个给定范围内的所有属性。使用方法如下:
- (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRangePointer)range;

这里,range可以知道有多少字符。NSRangePointer是一个指向NSRange的指针。
NSAttributedNString不是NSString。可以通过其实例方法string来得到NSString字符串。
- (NSString *)string;

比如,想得到NSAttributedString的一个子串。可以如下:
NSAttributedString *attributedString = ...;NSString *substring = ...;NSRange r = [[attributedString string] rangeOfString:substring];

NSMutableAttributesString

大部分时候,我们都是使用NSMutableAttributedString。
你可以为字符添加属性:
- (void)addAttributes:(NSDictionary *)attributes range:(NSRange)range;
这会设置指定属性的值,而不改变其他属性的值。

如果使用以下方法:
- (void)setAttributes:(NSDictionary *)attributes range:(NSRange)range;
该方法会设置新的属性覆盖所有的原有属性。

也可以指定range删除指定的属性:
- (void)removeAttribute:(NSString *)attributeName range:(NSRange)range;

改变字符串的内容

你可以插入、删除和替换字符。也可以使用NSMutableAttributedString方法:
- (NSMutableString *)mutableString;

来看一下Attributed Strings有哪些属性
1. NSFontAttributeName: 字体属性。
@{ NSFontAttributeName: [UIFont preferredFontWithTextStyle: UIFontTextStyleHeadline] }

2. NSForegroundColorAttributeName:  颜色属性(在设置文本颜色的时候我们要小心,一般通过颜色能表达出一定的信息,因此不要随便设置颜色)

3. NSStorkeWithAttributeName: @-5  填充属性,指定的宽度
如果是负数,就是"fill and stroke"
如果是正数,仅仅是stroke,描边,而不填充。
NSStrokeColorAttributeName:  指定颜色

4. NSUnderlineStyleAttributeName: 下划线属性
还有很多的属性,可以查看文档了解。看一个例子如下:
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];    paragraphStyle.alignment = NSTextAlignmentCenter;        UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];    font = [font fontWithSize:font.pointSize * 1.2];        NSString *text = @"Hello there! oh ye\n天知道,损有余而补不足。\n是故虚胜实,不足胜有余";        NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@", text] attributes:@{NSFontAttributeName: font,NSForegroundColorAttributeName:[UIColor greenColor],NSStrokeWidthAttributeName:@-2,NSStrokeColorAttributeName:[UIColor orangeColor],NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle),NSParagraphStyleAttributeName:paragraphStyle}];


得到如下结果:

0 0
原创粉丝点击