【问题标题】:TableView open url表视图打开网址
【发布时间】:2019-03-17 07:53:16
【问题描述】:

我有代码来加载从 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


【解决方案1】:

使用 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(string:"https://api.myjson.com/bins/oe3gu")

让 title = 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
        .....
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 2013-07-13
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多