gpt4 book ai didi

swift - 删除部分属性字符串而不删除属性

转载 作者:行者123 更新时间:2023-11-28 10:48:04 25 4
gpt4 key购买 nike

我试图删除属性字符串中的一些文本。如何在不删除属性的情况下执行此操作?

我尝试过的:

我在 SO ( Replace substring of NSAttributedString with another NSAttributedString ) 上找到了这篇文章,其中 OP 正在寻找与 NSString 的 stringByReplacingOccurrencesOfString:withString: NSAttributedString 等效的方法。我是 Swift 的新手,所以我无法理解已接受的答案。

我转向其他答案,如果它们不是用 objective-c 编写的,它们就是我无法编译的方法。

这是我所能得到的。我在 SO 上找不到任何其他帖子来解决我的问题。

最佳答案

要删除属性字符串的一部分,您需要使用 NSMutableAttributedString deleteCharacters(in:) 方法。

下面是一些示例代码:

// Create some attributes string
let attrs: [NSAttributedStringKey: Any] = [ .foregroundColor: UIColor.red, .font: UIFont.systemFont(ofSize: 24) ]
let attrStr = NSAttributedString(string: "Hello there", attributes: attrs)
print(attrStr)

// Create a mutable attributed string, find the range to remove and remove it
let mutStr = attrStr.mutableCopy() as! NSMutableAttributedString
let range = (mutStr.string as NSString).range(of: " there")
mutStr.deleteCharacters(in: range)
print(mutStr)

输出:

Hello there{    NSColor = "UIExtendedSRGBColorSpace 1 0 0 1";    NSFont = "<UICTFont: 0x7f989541d6c0> font-family: \".SFUIDisplay\"; font-weight: normal; font-style: normal; font-size: 24.00pt";}Hello{    NSColor = "UIExtendedSRGBColorSpace 1 0 0 1";    NSFont = "<UICTFont: 0x7f989541d6c0> font-family: \".SFUIDisplay\"; font-weight: normal; font-style: normal; font-size: 24.00pt";}

关于swift - 删除部分属性字符串而不删除属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47663448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com