AttributedString/Substring扩展:无法通过动态查找属性进行赋值:下标仅为只读。
创始人
2024-09-21 22:00:31
0

在对AttributedString/Substring类型进行扩展时,不能将其下标设置为可写的。可以使用方法或者计算属性来代替下标进行操作。

例如,将下标操作改写为方法:

extension AttributedString {
    func setAttribute(_ attribute: NSAttributedString.Key, value: Any, range: NSRange) -> AttributedString {
        let mutableAttributedString = NSMutableAttributedString(attributedString: self)
        mutableAttributedString.addAttribute(attribute, value: value, range: range)
        return AttributedString(mutableAttributedString)
    }
}

let attributedString = AttributedString("Hello, world!")
let range = NSRange(location: 0, length: 5)
let coloredString = attributedString.setAttribute(.foregroundColor, value: UIColor.red, range: range)

或者使用计算属性:

extension AttributedString {
    var foregroundColor: UIColor? {
        get {
            return attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor
        }
        set {
            if let color = newValue {
                addAttribute(.foregroundColor, value: color, range: NSRange(location: 0, length: length))
            } else {
                removeAttribute(.foregroundColor, range: NSRange(location: 0, length: length))
            }
        }
    }
}

let attributedString = AttributedString("Hello, world!")
attributedString.foregroundColor = UIColor.red

相关内容

热门资讯

围绕透视问题!智星德州插件怎么... 围绕透视问题!智星德州插件怎么下载,德普辅助app,其实真的是有挂(有挂方法)1、进入游戏-大厅左侧...
黑科技技巧!德普之星私人局辅助... 黑科技技巧!德普之星私人局辅助免费,德扑之星怎么开辅助,总是是有挂(有挂方法)1、起透看视 德普之星...
今日!wepoker辅助器安装... 今日!wepoker辅助器安装包,德普之星透视辅助软件,原来真的是有挂(真是有挂)所有人都在同一条线...
备受关注的!hhpoker辅助... 备受关注的!hhpoker辅助靠谱吗,德扑之星透视免费,一直存在有挂(确实有挂)1、德扑之星透视免费...
黑科技教程!wpk私人局辅助是... 黑科技教程!wpk私人局辅助是真的吗,德扑之星透视软件免费入口官网,好像确实有挂(有挂猫腻)1、这是...
据统计!wepoker辅助透视... 据统计!wepoker辅助透视软件,德普之星私人局透视,其实确实有挂(有挂方法)德普之星私人局透视辅...
备受关注的!wepoker怎么... 备受关注的!wepoker怎么挂底牌,德扑之星怎么设置埋牌,一贯是真的有挂(有挂头条)小薇(辅助器软...
出乎意料的是!德普之星透视免费... 出乎意料的是!德普之星透视免费,德扑圈透视,一直真的有挂(有挂详情)1、许多玩家不知道德普之星透视免...
反观!hh poker透视器下... 反观!hh poker透视器下载,德扑之星辅助工具如何打开,真是是有挂(有挂分析)1、操作简单,无需...
目前!德普之星怎么开辅助,德扑... 目前!德普之星怎么开辅助,德扑之星辅助器,竟然是有挂(有挂秘籍)所有人都在同一条线上,像星星一样排成...