【发布时间】:2018-10-25 10:38:13
【问题描述】:
在我们的应用中,我们有一个出站 VOIP 电话拨号器。
我想检测字符串中的数字并添加一个自定义操作,以便代替打开本机拨号器的默认行为,它将转到我们自己在应用程序中的拨号器并预先填充所选号码。
我的第一个想法是将消息正文放入一个字符串数组中,并检查每个单词是否为数字,然后创建一个属性字符串。但是我很难理解如何将属性字符串恢复为字符串,以及我什至会指定什么来打开带有预填充数字的所述屏幕。
我知道 NSDataDetector 可以列出在字符串中找到的数字,但我不知道如何用可点击操作替换这些特定部分并将其作为字符串返回。
如果有人有类似的经历,那么任何帮助将不胜感激?
注意 :此消息的正文显示在 UILabel 控件中。
更新
这是我到目前为止所拥有的......
func AddNumberLink() -> String {
let body = self
let wordsInBody = body.components(separatedBy: .whitespaces)
for i in 0..<wordsInBody.count {
var word = wordsInBody[i]
if word.isTelephoneNumeric {
let attributedString = NSMutableAttributedString(string:word)
attributedString.addAttribute(NSAttributedStringKey.link, value:"https://www.google.com",range: NSRange(location: 0, length: word.count))
attributedString.addAttribute(NSAttributedStringKey.foregroundColor,value: UIColor.red, range: NSRange(location:0, length: word.count))
word = attributedString.string
}
}
return body
}
【问题讨论】:
-
你能分享你到目前为止所做的代码或用更好的例子解释吗?
-
UITextView+NSDataDetector可能会触发UITextViewDelegate方法textView(_:shouldInteractWith:in:interaction:)。如果您希望它是可触摸的,请不要使用UILabel。这不是设计的。有允许它的外部库,但这不是它的最初目的。 2:30 见developer.apple.com/videos/play/wwdc2018/221
标签: ios swift string format nsattributedstring