swift - 表视图打开网址
问题描述
我有代码来加载从 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
解决方案
使用 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
.....
}
推荐阅读
- node.js - Next.js 受限页面和用户认证最佳实践
- python - Flask - 我无法从 flask_app 导入用户模型
- c++ - 空括号初始化的链接器错误
- firebase - 如何使用 React Native 和 Firebase 处理通知的“读取”标志?
- python-3.x - Matplotlib 颜色总和作为绘图重叠的结果
- python - 基于多个二进制列创建新的分类变量
- c++ - 使用 CRTP 的多态链中的两个继承级别
- javascript - setInterval 变为负数
- linux - 检查子目录是否存在压缩文件——如果不存在则压缩
- python - python kmedoids - 更有效地计算新的中心点