Reputation: 336
I want to clickable string. like :
By creating an account, you agree to the ABC Terms of Service and Privacy Policy.
I want to click event Terms of Service , Privacy Policy.
My app support also multi language. How can I do this with multi
language any advice please ?
Upvotes: 1
Views: 1238
Reputation: 7524
This solution should work for Swift 4
class YourClassViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var terms: UITextView!
let termsAndConditionsURL = "http://www.example.com/terms";
let privacyURL = "http://www.example.com/privacy";
override func viewDidLoad() {
super.viewDidLoad()
self.terms.delegate = self
let attributedString = NSMutableAttributedString(string: "termsString".localized())
var foundRange = attributedString.mutableString.range(of: "terms_and_conditions".localized())
attributedString.addAttribute(NSAttributedStringKey.link, value: termsAndConditionsURL, range: foundRange)
foundRange = attributedString.mutableString.range(of: "Privacy".localized())
attributedString.addAttribute(NSAttributedStringKey.link, value: privacyURL, range: foundRange)
terms.attributedText = attributedString
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
if (URL.absoluteString == termsAndConditionsURL) {
let myAlert = UIAlertController(title: "Terms", message: nil, preferredStyle: UIAlertControllerStyle.alert)
myAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(myAlert, animated: true, completion: nil)
} else if (URL.absoluteString == privacyURL) {
let myAlert = UIAlertController(title: "Conditions", message: nil, preferredStyle: UIAlertControllerStyle.alert)
myAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(myAlert, animated: true, completion: nil)
}
return false
}
}
Have a look that I use the localized extension from here https://stackoverflow.com/a/29384360/4420355
extension String {
func localized(withComment:String = "") -> String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: withComment)
}
}
In my projects I prefer this pod https://github.com/mac-cain13/R.swift
You have to deposit your text strings in your localizable for multi language. For a complete tutorial have a look at https://medium.com/lean-localization/ios-localization-tutorial-938231f9f881
//english
"terms_and_conditions" = "Terms and Condition";
"privacyURL" = "Privacy";
"termsString" = "By using this app you agree to our Terms and Conditions and Privacy Policy";
//german
"terms_and_conditions" = "Geschäftsbedingungen";
"privacy_url" = "Datenschutz";
"termsString" = "Wenn du diese App verwendest, stimmst du dem Datenschutz und den Geschäftsbedigungen zu";
If you need different links for the privacy and the terms you can add them to localizable too.
In this solution you handle multi language in a very easy way.
Upvotes: 2