I am trying to implement some feature:
I want a UITextView, which happens to be an address of some place, lead the user to the Apple Maps when tapping on this UITextView and show the location of the address in a UITextView. Any ideas on how I can do it?
What I have tried doing so far:
import MapKit
@IBOutlet weak var firstAddressTapped: UITextView!
func viewDidLoad() {
let attributedString = NSMutableAttributedString(string: "The address of my place")
attributedString.addAttribute(.link, value: "http://maps.apple.com/?daddr=The+address+of+my+place", range: NSRange(location: 19, length: 55))
firstAddressTapped.attributedText = attributedString
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
UIApplication.shared.open(URL)
return false
}
Thanks!
A great simple tutorial by Alexander Adelmaer on Medium helped me solve my problem! Enjoy.
https://medium.com/app-makers/how-to-add-a-tap-gesture-to-uilabel-in-xcode-swift-7ada58f1664
What I've done wrong:
Tried to implement the feature in a wrong file when I was supposed to add it to View Controller.
How I solved:
override func viewDidLoad() {
super.viewDidLoad()
self.setupLabelTap()
}
}
@objc func labelTapped(_ sender: UITapGestureRecognizer) {
if let url = URL(string: "http://maps.apple.com/?address=My+Address") {
UIApplication.shared.open(url)
}
print("The label is tapped!")
}
func setupLabelTap() {
let labelTap = UITapGestureRecognizer(target: self, action: #selector(self.labelTapped(_:)))
self.myView.labelAddress.isUserInteractionEnabled = true
self.myView.labelAddress.addGestureRecognizer(labelTap)
}
Moreover, you definitely don't need MapKIT to use UITapRecognizer to open the Apple Maps.