在NSAttributedString上具有多个具有不同属性的范围

时间:2015-02-19 05:26:43

标签: ios objective-c nsattributedstring

我有一个多线UILabel,我想增加线高,但我也希望它的一部分是不同的颜色,只有线高可以正常工作。但是一旦我尝试改变某个范围的颜色,它就会回到库存状态,没有任何一条线。

任何提示?这是在内容设置器中完成的。


- (void)setContent:(NSString *)content {
    _content = content;

    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:self.content];
    NSMutableAttributedString *mutableAttrString = [attributedString mutableCopy];

    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    [paragraphStyle setLineSpacing: 5.0f];

    NSDictionary *attributes = @{
                                 NSFontAttributeName: [UIFont fontWithName:@"BentonSans-Regular" size:16.0],
                                 NSParagraphStyleAttributeName: paragraphStyle
                                };
    NSDictionary *colorAttributes = @{
                   NSForegroundColorAttributeName: [UIColor redColor]
                   };
    [mutableAttrString addAttributes:attributes range:NSRangeFromString(self.content)];
    [mutableAttrString addAttributes:colorAttributes range:NSMakeRange(4, 8)];


    [self.label setAttributedText: mutableAttrString];
}

谢谢!

2 个答案:

答案 0 :(得分:2)

NSRangeFromString函数需要一个类似@"{3,10}"的字符串。换句话说,它需要一个包含两个数字的字符串,用于指定范围的起始位置和长度。我怀疑content字符串不是那样的字符串。

所以这一行

[mutableAttrString addAttributes:attributes range:NSRangeFromString(self.content)];

应该是

[mutableAttrString addAttributes:attributes range:NSMakeRange(0,mutableAttrString.length)];

答案 1 :(得分:0)

在viewdidLoad方法中

将字符串赋给self.content:

self.content = @"pass your text ";

//删除不需要的方法的第一行

- (void)setContent:(NSString *)content {

    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:self.content];
    NSMutableAttributedString *mutableAttrString = [attributedString mutableCopy];

    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    [paragraphStyle setLineSpacing: 5.0f];

    NSDictionary *attributes = @{
                                 NSFontAttributeName: [UIFont fontWithName:@"BentonSans-Regular" size:16.0],
                                 NSParagraphStyleAttributeName: paragraphStyle
                                };
    NSDictionary *colorAttributes = @{
                   NSForegroundColorAttributeName: [UIColor redColor]
                   };
    [mutableAttrString addAttributes:attributes range:NSRangeFromString(self.content)];
    [mutableAttrString addAttributes:colorAttributes range:NSMakeRange(4, 8)];


    [self.label setAttributedText: mutableAttrString];
}