2016-08-30 93 views
12

有了一個不可編輯的UITextView,我想嵌入這樣的文字iOS9 +:的UITextView與超鏈接文本

只是click here註冊

我可以創造一個功能和操作文本但有沒有更簡單的方法?

我看到,我可以用NSTextCheckingTypeLink因此讓文字也可以點擊沒有「點擊這裏」部分是直接在Interface Builder:

只是http://example.com註冊

我使用的Xcode 8和Swift 3,如果這是相關的。

回答

17

設置你的視圖控制器符合UITextViewDelegate和下面的代碼:

override func viewDidLoad() { 
    super.viewDidLoad() 

    // You must set the formatting of the link manually 
    let linkAttributes = [ 
     NSLinkAttributeName: NSURL(string: "https://www.apple.com")!, 
     NSForegroundColorAttributeName: UIColor.blue 
    ] as [String : Any] 

    let attributedString = NSMutableAttributedString(string: "Just click here to register") 

    // Set the 'click here' substring to be the link 
    attributedString.setAttributes(linkAttributes, range: NSMakeRange(5, 10)) 

    self.textView.delegate = self 
    self.textView.attributedText = attributedString 
} 

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { 
    return true 
} 
+0

UITextItemInteraction是iOS10 +,但我需要iOS9 +。我會看看我是否可以修復並在一秒之內爲此投票。 –

+1

在swift 4中,屬性已經從NSLinkAttributedName重命名爲.link,NSForegroundColorAttributeName重命名爲.foregroundColor –

0

我想做同樣的事情,最終只用一個UIButton與UILabels包圍的標題是「點擊這裏」「只是「和」註冊「,然後:

@IBAction func btnJustClickHereLink(_ sender: UIButton) { 
    if let url = URL(string: "http://example.com") { 
     UIApplication.shared.openURL(url) 
    } 
}