2016-11-19 1 views
0

У меня есть UITableView с пятью статическими ячейками.Как открыть URL-адрес через UITableViewCell

Я пытаюсь сделать это, когда я нажимаю одну из ячеек, он открывает конкретный 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

потребительных 'переопределение функ 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) возвратит ноль

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 из массива адресов для соответствующего выбранной строки из 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) 
     } 
    } 
Смежные вопросы