2016-11-30 34 views

回答

4

您可以使用UITextViewDelegateshouldChangeTextIn方法,并检查使用NSDataDetector

这里是斯威夫特3我的工作液

extension ViewController: UITextViewDelegate { 

    func checkURL(inputString: String) { 
     let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) 
     let matches = detector.matches(in: inputString, options: [], range: NSRange(location: 0, length: inputString.utf16.count)) 

     for match in matches { 
      let url = (inputString as NSString).substring(with: match.range) 
      print(url) 
     } 
    } 

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { 
     checkURL(inputString: textView.text) 
     return true 
    } 
} 

参考了NSDataDetectorhttps://www.hackingwithswift.com/example-code/strings/how-to-detect-a-url-in-a-string-using-nsdatadetector

+0

这真是太棒了。非常感谢您发布您的解决方案。为我节省了很多时间!并且很棒! –

相关问题