【发布时间】:2019-09-08 10:21:10
【问题描述】:
您好,我正在从这个站点 https://jsonplaceholder.typicode.com/posts 实现 json api
我只想查看用户在其他视图控制器中选择(按 id)的单元格的元素
如何发送当前标题、正文从选择当前索引单元格
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("How should i implement specific id ")
var userBySectionNumber = [(key: Int, value: [User])]()
var userById = [(key: Int, value: [User])]()
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
private func configureView() {
tableView.delegate = self
tableView.dataSource = self
let url = "https://jsonplaceholder.typicode.com/posts"
fetchUsers(using: url)
}
func load(with users: [User]) -> Void {
userBySectionNumber = Dictionary(grouping: users, by: { user in
user.userId ?? 0 }).sorted(by: { $0.0 < $1.0})
print(userBySectionNumber)
userById = Dictionary(grouping: users, by: { user in
user.id ?? 0 }).sorted(by: { $0.0 < $1.0})
tableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
print(userBySectionNumber)
return userBySectionNumber.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userBySectionNumber[section].value.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection
section: Int) -> String? {
return "Section Number \(userBySectionNumber[section].key)"
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "users",for: indexPath) as? customeCellTableViewCell{
let user = userBySectionNumber[indexPath.section].value[indexPath.row]
cell.dataModel(forModel: user)
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
}
}
here i fetch the url
func fetchUsers(using url: String){
let url = URL(string: url)!
let _ = URLSession.shared.dataTask(with: url){ (data,response,error)
in
guard let data = data else {return}
do{
let userFetch = try JSONDecoder().decode([User].self, from: data)
self.users = userFetch
self.load(with: userFetch)
} catch{
}
}.resume()
}
如何显示选定行(带有id、title和body)并在下一个视图控制器中发送的问题
【问题讨论】:
标签: json swift api tableview didselectrowatindexpath