2017-07-16 80 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'不起作用。在過去的日子裏,我必須手動設置鏈接屬性,或者將它顯示爲普通文本。很高興你找到了你自己的解決方案 –

相關問題