如何UILabel在Swift中强调一下?我搜索了Objective-C但却无法让它们在Swift中工作.
我正在尝试在我的Swift应用程序中为某些文本添加下划线.这是我目前的代码:
let text = NSMutableAttributedString(string: self.currentHome.name)
let attrs = [NSUnderlineStyleAttributeName:NSUnderlineStyle.PatternDash]
text.addAttributes(attrs, range: NSMakeRange(0, text.length))
homeLabel.attributedText = text
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误text.addAttributes:
NSString与...不完全相同NSObject
如何将枚举中包含的属性添加到Swift中的NSMutableAttributedString?
NSInvalidArgumentException将项目升级到Swift 4.2(从4.0转换)后,我遇到异常.
2018-09-19 15:37:33.253482+0100 <redacted>-beta[3715:1010421] -[Swift._EmptyArrayStorage _getValue:forType:]: unrecognized selector sent to instance 0x107e6c290
2018-09-19 15:37:33.254312+0100 <redacted>-beta[3715:1010421] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Swift._EmptyArrayStorage _getValue:forType:]: unrecognized selector sent to instance 0x107e6c290'
Run Code Online (Sandbox Code Playgroud)
它是与a相关的东西NSMutableAttributedString和它添加一些属性的代码,例如,a NSAttributedString.Key.underlineStyle.
即将分配属性字符串时会发生异常: textView.attributedText = mutableAttributedString.
所以,它在Swift 4中工作:
mutableAttributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.styleNone.rawValue, range: range)
然后,使用Swift 4.2,编译器建议更改NSUnderlineStyle.styleNone.rawValue为NSUnderlineStyle.none.rawValue
之后,编译器开始大喊" 'none'不可用:使用[]构造一个空选项集 ":
mutableAttributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.none.rawValue, range: range)
^~~~~ 'none' is unavailable: use [] to construct an empty option set
Run Code Online (Sandbox Code Playgroud) 我有以下代码来尝试为标签的字符串添加下划线。
let attributedString = NSMutableAttributedString(string: "Hello World!")
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single, range: NSRange.init(location: 0, length: attributedString.length))
label.attributedText = attributedString
Run Code Online (Sandbox Code Playgroud)
但是,运行代码时,标签显示Hello World!没有下划线。
我正在运行 Xcode 12.4,并使用 iOS 14.4 iPhone 12 Pro Max 模拟器。