我的表格 View 单元格中有一个关注按钮,当我点击它时,我通过将我的用户 ID 和他的用户 ID 发送到 API 路由来关注用户。
var fbFriends = [People]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: FBFriendsTableViewCell = tableView.dequeueReusableCell(withIdentifier: "fbFriendsCell", for: indexPath) as! FBFriendsTableViewCell
cell.friendFollowButton.addTarget(self, action: #selector(followButtonTapped(_:)), for: .touchUpInside)
return cell
}
@objc func followButtonTapped(_ sender: UIButton) {
user.followUser(token: Helper.shared.getAccessToken()!, userId: Helper.shared.retriveUserID()!, followeeId: fbFriendsData[indexPath.row].userId) { (status, code, err, msg, body) in
//Do something with response
}
}
我需要的是发送我将在选择器参数中关注的用户的 id,以便我可以在 followUser
函数中使用它,而不是 indexPath.row
这已经超出了 tableView 闭包的范围。所以我需要的是这样的东西。
@objc func followButtonTapped(_ sender: UIButton, _ rowIndex: Int) {
user.followUser(token: Helper.shared.getAccessToken()!, userId: Helper.shared.retriveUserID()!, followeeId: fbFriendsData[rowIndex].userId) { (status, code, err, msg, body) in
//Do something with the response
}
}
最佳答案
您无法将参数传递给选择器。既然您正在创建一个按钮,为什么不直接将按钮标签设置为用户的 id,然后在您的 followButtonTapped
中,只需使用 sender.tag
访问它。
所以:
var fbFriends = [People]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: FBFriendsTableViewCell = tableView.dequeueReusableCell(withIdentifier: "fbFriendsCell", for: indexPath) as! FBFriendsTableViewCell
cell.friendFollowButton.tag = fbFriends[indexPath.row].userId
cell.friendFollowButton.addTarget(self, action: #selector(followButtonTapped(_:)), for: .touchUpInside)
return cell
}
@objc func followButtonTapped(_ sender: UIButton) {
user.followUser(token: Helper.shared.getAccessToken()!, userId: Helper.shared.retriveUserID()!, followeeId: sender.tag) { (status, code, err, msg, body) in
//Do something with response
}
}
关于swift - 将多个参数添加到 UITableView 中的目标 #selector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46915723/