Difference Between EffectiveRange and LongestEffectiveRange

泄露秘密 提交于 2019-12-04 09:53:50

Let's say you have this kind of attributes:
Range [0,2]: Black Background Color
Range [0,2]: Bold Font
Range [2,4]: Black Background Color
Range [2,4]: Italic Font

If you log this NSAttributedString, its attributes will be separated in two:
Range [0,2]: Black Background Color AND Bold Font
Range [2,4]: Black Background Color AND Italic Font
These attributes works like a NSDictionary, they are 2 different at two ranges.

If you use longestEffectiveRange at index 0 for NSBackgroundColorAttributeName, you'll get a range of [0,4].
If you use effectiveRange, you'll get [0,2].
In other words, the longestEffectiveRange will check if there is on the next index (after the end of effectiveRange) that may have another dictionary of attributes if it shares the wanted value with it and then append the range.

Sample Code:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"BoBiBu"];

[attributedString addAttribute:NSBackgroundColorAttributeName
                         value:[UIColor blackColor]
                         range:NSMakeRange(0, 2)];
[attributedString addAttribute:NSFontAttributeName
                         value:[UIFont boldSystemFontOfSize:12]
                         range:NSMakeRange(0, 2)];
[attributedString addAttribute:NSFontAttributeName
                         value:[UIFont italicSystemFontOfSize:12]
                         range:NSMakeRange(2, 2)];
[attributedString addAttribute:NSBackgroundColorAttributeName
                         value:[UIColor blackColor]
                         range:NSMakeRange(2, 2)];
NSLog(@"AttributedString: %@", attributedString);


NSRange range1;
NSLog(@"Attribute: %@", [attributedString attribute:NSBackgroundColorAttributeName atIndex:0 effectiveRange:&range1]);
NSLog(@"EffectiveRange of previous attribute: %@", NSStringFromRange(range1));

NSRange range2;
NSLog(@"Attribute: %@", [attributedString attribute:NSBackgroundColorAttributeName atIndex:0 longestEffectiveRange:&range2 inRange:NSMakeRange(0, 6)]);
NSLog(@"Longest effective Range of previous attribute: %@", NSStringFromRange(range2));

Logs:

> AttributedString: Bo{
    NSBackgroundColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICTFont: 0x7fd3e2f80ec0> font-family: \".HelveticaNeueInterface-MediumP4\"; font-weight: bold; font-style: normal; font-size: 12.00pt";
}Bi{
    NSBackgroundColor = "UIDeviceWhiteColorSpace 0 1";
    NSFont = "<UICTFont: 0x7fd3e2f83310> font-family: \".HelveticaNeueInterface-Italic\"; font-weight: normal; font-style: italic; font-size: 12.00pt";
}Bu{
}
> Attribute: UIDeviceWhiteColorSpace 0 1
> EffectiveRange of previous attribute: {0, 2}
> Attribute: UIDeviceWhiteColorSpace 0 1
> Longest effective Range of previous attribute: {0, 4}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!