swift - 将多个参数添加到 UITableView 中的目标 #selector

标签 swift function uitableview arguments selector

我的表格 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/

相关文章:

JavaScript - 从函数外部访问数组

python - 将多个项目添加到字典中

swift - 使用 coredata 时,在搜索栏取消按钮后 tableview.reloaddata() 不起作用

ios - 未调用 UITableView titleForHeaderInSection

ios - 从 JSON 中获取字典的值

ios - 类型 'AnimationView?' 的值没有成员 'setAnimation'

ios - 如何快速确定哪个文本字段处于事件状态

swift - 为调用异步方法的异步调度队列实现完成处理程序

Javascript:在另一个方法中调用一个方法

ios - 表格滚动时自动取消选中行