2017-07-16 33 views
1

我有一个UITextView,其中包含大量带有数字的文本。我试图检测文本视图中的数字,但无法实现。我只能找到解决方案来找到链接。在UiTextView中插入一个数字并检测数字

我正在使用NSAttributedString来显示文本。

.dataDetectorTypes似乎不起作用。任何一个可以帮助我

我想这样。

let middleTextView: UITextView = { 
     let tv = UITextView(); 
     let attributedText = NSMutableAttributedString(string: "Your NetCode will be sent to", attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 14)]); 
     attributedText.append(NSAttributedString(string: "\n\nXXXX XXX 252", attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 16)])); 
     attributedText.append(NSMutableAttributedString(string: "\n\n To update you mobile number call tel://13 2221", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)])); 
//  let url = NSURL(string: "tel://\(1234)"); 
//  tv.text = url; 
     tv.attributedText = attributedText; 
     tv.textAlignment = .center 
     tv.backgroundColor = UIColor.clear; 
     tv.dataDetectorTypes = .phoneNumber; 
     tv.isEditable = false; 
     tv.isSelectable = false; 
     tv.translatesAutoresizingMaskIntoConstraints = false; 
     return tv; 
    }(); 
+0

什么是你想回去?电话号码'13 2221'? –

+0

是的,我想要13 2221被点击,以便呼叫选项得到提示 – Bikram

回答

2

我看到你使用的是Swift 4的NSAttributedStringKey,所以我在你的问题中加了标签。

您必须手动进行电话URL,并设置isSelectable = true否则没有相互作用可以从文本视图中发生:

let middleTextView: UITextView = { 
    let attributedText = NSMutableAttributedString(string: "Your NetCode will be sent to", attributes: [.font : UIFont.systemFont(ofSize: 14)]) 
    attributedText.append(NSAttributedString(string: "\n\nXXXX XXX 252", attributes: [.font: UIFont.boldSystemFont(ofSize: 16)])) 
    attributedText.append(NSAttributedString(string: "\n\n To update you mobile number ", attributes: [.font: UIFont.systemFont(ofSize: 12)])) 

    let phoneNumber = "13 2221" 
    let phoneNumberAttributes: [NSAttributedStringKey: Any] = [ 
     .font: UIFont.systemFont(ofSize: 12), 
     .foregroundColor: UIColor.blue, 
     .link: URL(string: "tel://" + phoneNumber.replacingOccurrences(of: " ", with: ""))!, 
    ] 
    attributedText.append(NSAttributedString(string: phoneNumber, attributes: phoneNumberAttributes)) 

    tv.attributedText = attributedText 
    tv.textAlignment = .center 
    tv.backgroundColor = UIColor.clear 
    tv.isEditable = false 
    tv.isSelectable = true // you must set this to true 
    return tv 
}() 
+0

谢谢,它按预期工作。电话号码的颜色是蓝色,前景色不起作用。你知道我们如何将前景色变成黑色。 – Bikram

+0

.foregroundColor不起作用。但通过使用TextView.tintColor = UIColor.black – Bikram

+0

解决了'.foregroundColor'不起作用。在过去的日子里,我必须手动设置链接属性,或者将它显示为普通文本。很高兴你找到了你自己的解决方案 –