gpt4 book ai didi

ios - 在 Swift 中将 NSUnderlineStyle.PatternDash 添加到 NSAttributedString?

转载 作者:IT王子 更新时间:2023-10-29 05:12:44 25 4
gpt4 key购买 nike

我正在尝试为我的 Swift 应用程序中的某些文本添加下划线。这是我目前的代码:

let text = NSMutableAttributedString(string: self.currentHome.name)

let attrs = [NSUnderlineStyleAttributeName:NSUnderlineStyle.PatternDash]

text.addAttributes(attrs, range: NSMakeRange(0, text.length))
homeLabel.attributedText = text

但我在 text.addAttributes 行收到此错误:

NSString is not identical to NSObject

如何在 Swift 中将枚举中包含的属性添加到 NSMutableAttributedString?

最佳答案

下面是创建带下划线文本的 UILabel 的完整示例:

swift 5:

let homeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))

let text = NSMutableAttributedString(string: "hello, world!")

let attrs = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.patternDash.rawValue | NSUnderlineStyle.single.rawValue]

text.addAttributes(attrs, range: NSRange(location: 0, length: text.length))

homeLabel.attributedText = text

swift 4:

let homeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))

let text = NSMutableAttributedString(string: "hello, world!")

let attrs = [NSAttributedStringKey.underlineStyle: NSUnderlineStyle.patternDash.rawValue | NSUnderlineStyle.styleSingle.rawValue]

text.addAttributes(attrs, range: NSRange(location: 0, length: text.length))

homeLabel.attributedText = text

swift 2:

Swift 允许您将 Int 传递给采用 NSNumber 的方法,因此您可以通过删除对 NSNumber< 的转换来使其更清晰一些:

text.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: NSMakeRange(0, text.length))

注意:此答案之前使用的是原始问题中使用的 toRaw(),但现在不正确,因为 toRaw() 已被属性 取代>rawValue 从 Xcode 6.1 开始。

关于ios - 在 Swift 中将 NSUnderlineStyle.PatternDash 添加到 NSAttributedString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25611716/

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