使用按钮和文本字段打开链接

时间:2018-05-02 19:00:12

标签: swift xcode

我是否可以使用按钮和文本字段打开链接,该链接在应用程序本身的另一个页面上列出,而不是使用Safari?

我使用的是Swift 4

enter image description here

2 个答案:

答案 0 :(得分:0)

使用WKWebView打开Button动作上的链接 导入WebKit 导入WebKit

  

在您的FirstViewController中,在推送时传递URL   SecondViewController

<强> FirstViewController

if let secondVC = (UIStoryboard.init(name: "Main", bundle: nil)).instantiateViewController(withIdentifier: "secondVCID") {
    secondVC.url = textFiled.text // OR send the URL you want to send
    self.navigationController?.pushViewController(secondVC, animated: true)
}

在SecondViewController中

Import Webkit

声明委托

class SecondViewController: UIViewController,WKNavigationDelegate  {
  

声明URL var,以便u cab访问它FirstVC

var url: String?
@IBOutlet weak var webView: WKWebView!


In ViewDidLoad Of SecondVC

let webUrl = NSURL(string: url!)
let request = NSURLRequest(URL: webUrl)

// load request in webview.
webView.navigationDelegate = self
webView.loadRequest(request)

并实现WKWebview的所有委托方法

//MARK:- WKNavigationDelegate

func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
    print(error.localizedDescription)
}
func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    print("Strat to load")
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
    print("finish to load")
}

答案 1 :(得分:0)

您必须在目标视图控制器中打开webview,并将url字符串从第一个视图控制器发送到目标,如下所示:

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!

    @IBAction func action(_ sender: Any) {

        if let mainVC = storyboard?.instantiateViewController(withIdentifier: "second") as? DestinationViewController {
            mainVC.urlStr = textField.text
            self.navigationController?.pushViewController(mainVC, animated: true)

        }
    }
}
  

目标视图控制器:

class DestinationViewController: UIViewController {
    var urlStr: String?

    override func viewDidLoad() {
        super.viewDidLoad()
        let webView = UIWebView(frame: self.view.frame)
        self.view.addSubview(webView)

        if let urlString = urlStr, let url = URL(string: urlString) {
            webView.loadRequest(URLRequest(url: url))
        }
    }
}