首页 > 解决方案 > Swift如何将超链接添加到按钮

问题描述

因此,当我单击按钮打开网站链接但由于某种原因无法正常工作时,我正在尝试。我看过 2020 年的视频,对于那个工作的人来说,但对我来说,它给了我错误,这里是错误的图像。

错误

这是代码

import UIKit

class ContactViewController: UIViewController {

@IBAction func FB(_ sender: Any) {

}
@IBAction func YT(_ sender: Any) {
    UIApplication.shared.open(URL(string: "www.google.com")!)
}
@IBAction func URL(_ sender: Any) {
}
@IBAction func CALL(_ sender: Any) {
}


override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

我希望每个按钮都只链接一个名为具有电话号码的呼叫并直接进入电话拨号器。

编辑

错误

标签: iosswiftxcode

解决方案


而不是强制转换使用此代码

@IBAction func YT(_ sender: Any) {

      if let url = URL(string: "www.google.com") {
        UIApplication.shared.open(url)
      } else {
        print("url is not correct")
      }


    }


@IBAction func CALL(_ sender: Any) {
if let url = URL(string: "telprompt://\(phoneNumber)") {
        let application = UIApplication.shared
        guard application.canOpenURL(url) else {
            return
        }
        application.open(url, options: [:], completionHandler: nil)
    }
}

对于电子邮件导入 MessageUI

import MessageUI
@IBAction func Email(_ sender: Any) {
if MFMailComposeViewController.canSendMail() {
        let mail = MFMailComposeViewController()
        mail.mailComposeDelegate = self
        mail.setToRecipients(["you@yoursite.com"])
        mail.setMessageBody("<p>You're so awesome!</p>", isHTML: true)

        present(mail, animated: true)
    } else {
        // show failure alert
    }
}

推荐阅读