首页 > 解决方案 > 表视图打开网址

问题描述

我有代码来加载从 api 返回的结果https://api.myjson.com/bins/oe3gu

let url = URL(string:"https://api.myjson.com/bins/oe3gu")
        let task = URLSession.shared.dataTask(with: url!) {
            data, responese, error in

            if error != nil {
                print(error!)
            } else {
                if let dataContent = data {
                    do {
                        let result = try JSONSerialization.jsonObject(with: dataContent, options: JSONSerialization.ReadingOptions.mutableContainers)
                        print(result)

                    } catch {
                        print("Json Faild")
                    }
                }
            }
        }
        task.resume()

如何将标题放在 tableView 的单元格标签中,然后当我单击单元格时,我想在浏览器中打开 url

标签: swift

解决方案


使用 TVCell 的常用代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: REUSE_ID, for: indexPath) as! TripTableViewCell

    // Configure the cell...        
    let row = indexPath.row
    // take a part fo url.. 
    let title = ...[row]
    cell.textLabel.text = title

……

例如,您可以:

.. url = URL(字符串:“ https://api.myjson.com/bins/oe3gu ”)

让标题 = url.lastPathComponent

如果“oe3gu”就足够了。

我会更喜欢:

类 TableViewController: UITableViewController {

typealias InfoTuple = (String,String)

let myInfo :[InfoTuple] = [
    ("https://api.myjson.com/bins/oe3gu" , "link 1"),
    ("https://api.myjson.com/bins/oe3gu2" , "link 2"),
    ("https://api.myjson.com/bins/oe3gu2" , "link 3"),
]

override func viewDidLoad() {
    super.viewDidLoad()
}


// MARK: - Table view data source


override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return myInfo.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

    // Configure the cell...
    let row = indexPath.row
    let (title, _) = myInfo[row]
    cell.textLabel?.text = title
    return cell
}

……

你的代码将是:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let row = indexPath.row
    let (_, url) = myInfo[row]

    let task = URLSession.shared.dataTask(with: url!) {
        data, responese, error in
        .....
}

推荐阅读