如果我使用以下相同的函数为带有UILabel和UITextView的属性字符串设置一些属性,则两种情况下的显示看起来都相同,但是我无法点击UILabel的链接(用户交互为已启用)。
为什么UILabel不响应点击,而UITextVIew响应,如何使UILabel表现得像UITextVIew?
我看到了一个过去的问题,答案是为UILabel设置dataDetectors,但这一定是针对旧版本的Swift的,因为它不再存在,而且我也没有看到类似的替代方案。 / p>
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
}
答案 0 :(得分:0)
一个能响应点击的import re
rgx = "^\d*\.?\d*$"
if re.match(rgx, x):
print("it's a number!")
x = float(x)
是UILabel
,我建议您将UIButton
换成一个按钮并相应地设置其样式。然后,您只需将UILabel
挂接到它上,它将起作用。
IBAction
默认响应互动