代码之家  ›  专栏  ›  技术社区  ›  Z S

NSAttribute字符串:检查NSRange是否有效

  •  0
  • Z S  · 技术社区  · 6 年前

    我试着这样做:

    [mutableAttributedString enumerateAttribute:NSFontAttributeName inRange:underlineRange  options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id  value, NSRange range, BOOL * _Nonnull stop) {
    ....
    

    然而 underlineRange 可以通过某种方式进行操纵,使其脱离 mutableAttributedString 范围。在这种情况下,它最终会导致异常。

    处理这个案子最好的办法是什么?我找不到任何nsattributestring方法可以让您验证一个范围对于给定的属性字符串是否有效。

    1 回复  |  直到 6 年前
        1
  •  1
  •   rob mayoff    6 年前
    NSRange underlineRange = ...;
    
    NSRange fullRange = NSMakeRange(0, mutableAttributedString.length);
    underlineRange = NSIntersectionRange(underlineRange, fullRange);
    if (underlineRange.length == 0) {
        // intersection is empty - underlineRange was entirely outside the string
    } else {
        // underlineRange is now a valid range in mutableAttributedString
    }