【发布时间】:2019-09-22 04:37:24
【问题描述】:
如果我使用下面的相同函数为带有 UILabel 和 UITextView 的属性字符串设置一些属性,那么两种情况下的显示看起来都是一样的,但我无法点击 UILabel 的链接(用户交互是已启用)。
为什么 UILabel 不响应点击而 UITextVIew 响应,如何使 UILabel 表现得像 UITextVIew?
我看到了一个过去的问题,答案是为 UILabel 设置 dataDetectors,但这一定是针对旧版本的 Swift,因为它不再存在,而且我没有看到任何类似的替代方案。
class MyViewController: UIViewController {
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var textView1: UITextView!
let kTextContent = "This is some text with bold and link1 and link2 and color."
let kBoldText = "bold"
let kLink1Text = "link1"
let kLink2Text = "link2"
let kColorText = "color"
let kUrl1 = "http://www.google.com"
let kUrl2 = "http://www.apple.com"
override func viewDidLoad() {
super.viewDidLoad()
label1.text = kTextContent
label1.attributedText = setAttributes(theAttributedString: label1.attributedText?.mutableCopy(with: nil) as! NSMutableAttributedString)
textView1.text = kTextContent
textView1.attributedText = setAttributes(theAttributedString: textView1.attributedText?.mutableCopy(with: nil) as! NSMutableAttributedString)
}
func setAttributes(theAttributedString: NSMutableAttributedString) -> NSMutableAttributedString
{
let boldRange = theAttributedString.mutableString.range(of: kBoldText)
let boldFontAttribute: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20)]
theAttributedString.addAttributes(boldFontAttribute, range: boldRange)
let link1Range = theAttributedString.mutableString.range(of: kLink1Text)
theAttributedString.addAttribute(.link, value: kUrl1, range: link1Range)
theAttributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: link1Range)
let link2Range = theAttributedString.mutableString.range(of: kLink2Text)
theAttributedString.addAttribute(NSAttributedString.Key.link, value: kUrl2, range: link2Range)
theAttributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: link2Range)
let colorRange = theAttributedString.mutableString.range(of: kColorText)
theAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: colorRange)
return theAttributedString
}
【问题讨论】:
-
这是从 iOS 开始的正常行为。请参阅我解释原因的链接相关答案,并且一定要查看 WWDC 视频。
标签: ios swift uilabel uitextview nsattributedstring