2016-11-19 89 views
0

我有一個UITableView五個靜態單元格。如何通過UITableViewCell打開URL

我試圖做到這一點,當我點擊其中一個單元格時,它會打開一個特定的URL。每個單元格都有其唯一的URL。

我該怎麼做?

使用Swift 3,Xcode。

謝謝!

代碼:

import UIKit 
import Kingfisher 

class SettingsTableView: UITableViewController { 

    @IBAction func clearCache(_ sender: Any) { 


     ImageCache.default.clearMemoryCache() 

     ImageCache.default.clearDiskCache() 

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

     self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] 

     self.navigationController!.navigationBar.barTintColor = UIColor.black 

    } 

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

    override func viewWillAppear(_ animated: Bool) { 
     self.navigationController?.hidesBarsOnTap = false 

    } 

    override var prefersStatusBarHidden: Bool { 
     return true 
    } 

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    } 

} 
+0

使用 - '覆蓋FUNC的tableView(_的tableView:UITableView的,didSelectRowAt indexPath:IndexPath){ //你的代碼... }' – iDeveloper

+0

@iDeveloper我不知道我的理解。您能否將該代碼作爲回覆發佈?謝謝。 – Miles

+0

你想打開URL,點擊tableViewCell? – iDeveloper

回答

0

假設你有,你是出列的自定義單元格類var urlToBeOpened : String屬性。

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
       let cell = tableView.cellForRowAtIndexPath(indexPath) as! CustomTableViewCell 
       let urlAsString = cell.urlToBeOpened 
       let url = URL(string : urlAsString) 
       UIApplication.sharedApplication().openURL(url) 

} 

確認urlToBeOpened字符串是URL編碼或URL(string : urlAsString)將返回nil

0

裏面你didSelectRowAt indexPath功能,你將不得不調用open,而不是openURL

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    let url = URL(string: self.urlArray[indexPath.row])! 
    UIApplication.shared.open(url, options: [:]) 
} 
0

聲明全局數組(在你的班級內)用這樣的鏈接

let links = ["http://google.com", "https://apple.com"] 

然後在didSelectRowAt只需打開你的鏈接

let link = links[indexPath.row] 
if let url = URL(string: link){ 
    UIApplication.shared.open(url, options: [:], completionHandler: nil) 
} //else you entered an incorrect link 
0

簡單地實現UITableViewDelegate方法didSelectRowAt並打開URL的數組的URL對應UITableView的選定行。

let urlArray = ["http://google.com", "https://apple.com"] 

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
    { 
     let urlString = self.urlArray[indexPath.row] 
     if let url = URL(string: urlString) 
     { 
      UIApplication.shared.openURL(url) 
     } 
    }