你好,我正在从这个站点实现 json api https://jsonplaceholder.typicode.com/posts
我只想查看用户在其他 View Controller 中选择(通过 id)的单元格的 elemnet
如何从选择当前索引单元格发送当前标题、正文
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、标题和正文)并将其发送到下一个 View Controller 的问题
最佳答案
您可以创建名为selectedUser 的User 变量来保存选定的User。当您点击任何单元格时,您应该在 didSelectRowAt 方法中将所选用户分配给此变量。
同样在OtherViewController中:
- 添加一个用户变量。
最后,在您的prepareForSegue 方法中:
你应该这样做:
self.selectedUser = otherVC.user
关于json - 如何将 TableView 中的选定行(JSON)发送到另一个 View Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57841045/