在 UITableView 中向目标#selector 添加多个参数

Adding multiple arguments to a target #selector in a UITableView

我的 table 视图单元格中有一个关注按钮,当我单击它时,我通过将我的用户 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 table查看关闭。所以我需要的是这样的东西。

 @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
    }
}