簡體   English   中英

NSAttributedString:檢查NSRange是否有效

[英]NSAttributedString: check if NSRange is valid

給定一個NSRange和一個NSAttributedString,什么是最好的方法來驗證范圍是有效的,並且不會超出屬性字符串的界限?

我正在嘗試這樣做:

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

但是, underlineRange可以以超出mutableAttributedString范圍的方式進行操作。 在這種情況下,它最終會導致異常。

處理此案的最佳方法是什么? 我找不到任何NSAttributedString方法,可用於驗證范圍對於給定的屬性字符串有效。

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM