如何在swift中执行可点击的字符串?

时间:2018-03-04 08:10:38

标签: swift click uilabel

我想要点击字符串。喜欢:

创建帐户即表示您同意ABC 服务条款隐私政策

我想点击活动服务条款,隐私政策。

我的应用程序支持多种语言。我怎么能用multi

做到这一点

语言有什么建议吗?

1 个答案:

答案 0 :(得分:1)

此解决方案适用于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
 }
}

看看我使用本地https://stackoverflow.com/a/29384360/4420355

的本地化扩展程序
extension String {
    func localized(withComment:String = "") -> String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: withComment)
    }
}

在我的项目中,我更喜欢这个广告容器https://github.com/mac-cain13/R.swift

您必须将文本字符串存放在本地化的多语言中。 有关完整的教程,请查看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";

如果您需要隐私和条款的不同链接,您也可以将其添加到本地化。

在此解决方案中,您可以非常轻松地处理多语言。