加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – NSAttributedString获取超出范围的属性异常

发布时间:2020-12-14 04:38:24 所属栏目:百科 来源:网络整理
导读:我正在尝试从属性字符串中获取属性.除非字符串为空,否则一切正常.看一看: let s = NSAttributedString(string: "",attributes: [NSForegroundColorAttributeName: UIColor.red])let range = NSMakeRange(0,s.length)let attrs = s.attributes(at: 0,longest
我正在尝试从属性字符串中获取属性.除非字符串为空,否则一切正常.看一看:

let s = NSAttributedString(string: "",attributes: [NSForegroundColorAttributeName: UIColor.red])
let range = NSMakeRange(0,s.length)
let attrs = s.attributes(at: 0,longestEffectiveRange: nil,in: range)

为什么我在最后一行超出界限?

解决方法

这是预期的结果.如果字符串的长度为0(“”的情况),它在索引0处没有字符,因此当您尝试使用s.attributes访问它时,您应该得到一个越界异常.

由于索引从0开始,因此仅对String.length> 0存在index = 0.

您可以使用长度为1的字符串并在s.attributes中输入1来轻松检查.

let s = NSAttributedString(string: "a",s.length)
let attrs = s.attributes(at: 1,in: range)    //also produces out of bounds error

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读