2014-11-14 106 views
3

我使用的是swift,因为它是一种相当新的编程语言,所以没有太多的文档。 我正在尝试使按钮充当超链接。我创建了一个IBAction,但我不知道从哪里去。这里是我的代码:制作按钮超链接Swift

import UIKit 

class ViewController: UIViewController { 

    @IBAction func WebLink(sender: AnyObject) { 

    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

} 
+0

查看此文章:http://stackoverflow.com/questions/25477547/how-can-i-create-a-hyperlink-with-swift – Glynbeard 2014-11-14 21:24:17

回答

16

您可以通过调用openURL方法上的UIApplication实例中打开一个URL:

@IBAction func WebLink(sender: AnyObject) { 
    if let url = NSURL(string: "http://...") { 
     UIApplication.sharedApplication().openURL(url) 
    } 
} 
0

对于斯威夫特3的OpenURL已被弃用。

取而代之的是开放这需要选择和完成处理程序:

sharedApplication()也被替换共享财产。

if let url = URL(string: "https://...") { 
    UIApplication.shared.open(url, options: [:]) { 
     boolean in 
     // do something with the boolean 
    } 
} 
0

API在低于iOS 10的版本中不可用,所以需要添加以下内容。

guard let url = URL(string: "https://www.google.com/") else { 
    return 
} 
if #available(iOS 10.0, *) { 
    UIApplication.shared.open(url, options: [:]) {_ in } 
} else { 
    // Fallback on earlier versions 
    UIApplication.shared.openURL(url) 
}