Swift如何将超链接添加到按钮

时间:2020-05-10 00:00:39

标签: ios swift xcode

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

Errors

这是代码

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.
}

我希望每个按钮仅链接一个名为CALL的CALL,以拥有一个电话号码并直接进入电话机。

编辑

Error

1 个答案:

答案 0 :(得分:0)

使用此代码代替强制转换

@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
    }
}