How to display clickable links in UITextView
Just select the UITextView
in your storyboard and go to "Show Attributes inspector" and select selectable
and links
. As the image below shows. Make sure Editable
is unchecked.
Can't make URL clickable in UITextView
The issue was that User Interaction Enabled
wasn't checked at the bottom of the View section of IB's Attributes Inspector.
UITextView with hyperlink text
Set isEditable = false
or the text view will go into text-editing mode when user taps on it.
Swift 4 and later
let attributedString = NSMutableAttributedString(string: "Just click here to register")
let url = URL(string: "https://www.apple.com")!
// Set the 'click here' substring to be the link
attributedString.setAttributes([.link: url], range: NSMakeRange(5, 10))
self.textView.attributedText = attributedString
self.textView.isUserInteractionEnabled = true
self.textView.isEditable = false
// Set how links should appear: blue and underlined
self.textView.linkTextAttributes = [
.foregroundColor: UIColor.blue,
.underlineStyle: NSUnderlineStyle.single.rawValue
]
Trigger hyper link text click and and normal text click in UITextView
A possible solution is to add a "fake URL" (like a "internal URL Scheme look alike) where there is no link attribute:
attributedText.enumerateAttribute(.link, in: NSRange(location: 0, length: attributedText.length), options: []) { (attribute, range, pointee) in
//If there is no URL => Set our custom one
if attribute == nil {
attributedText.addAttribute(.link, value: "com.myapp.custom", range: range)
}
}
And in this delegate method, check the value of URL
.
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
print("url: \(URL)")
if url == ... {} else { ... }
return false
}
Related Topics
Avaudioplayer Throws Breakpoint in Debug Mode
How to Set Imageview in Circle Like Imagecontacts in Swift Correctly
How to Use Static Cells in Uitableview Without Using Storyboards
How to Do Programmatically Gradient Border Color Uibutton with Swift
How to Combine Two Dictionary Instances in Swift
How to Make a Function Execute Every Second in Swift
Presenting a View Controller Modally from an Action Sheet's Delegate in iOS8 - iOS11
How to Enable Arc Project-Wide in Xcode 4.2
How to Set Cmake_C_Compiler and Cmake_Cxx_Compiler for Building Assimp for iOS
Wireless iPhone App Distribution - Problem with Itms-Services Protocol
Attempting to Load the View of a View Controller While It Is Deallocating... Uisearchcontroller
Google Maps iOS Sdk, Getting Current Location of User
iPhone Image Captured from Camera Rotate -90 Degree Automatically
Why Safari Shows "No Inspectable Applications" During Remote Debugging with iOS 6 Device
Performseguewithidentifier Very Slow When Segue Is Modal
Uikeyboardframebeginuserinfokey & Uikeyboardframeenduserinfokey