【问题标题】:Adding multiple arguments to a target #selector in a UITableView在 UITableView 中向目标#selector 添加多个参数
【发布时间】:2017-10-24 16:36:00
【问题描述】:

我的表格视图单元格中有一个关注按钮,当我点击它时,我通过将我的用户 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 函数中使用它,而不是已经在 tableView 闭包之外的 indexPath.row。所以我需要的是这样的东西。

 @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

    }
}

【问题讨论】:

    标签: swift function uitableview arguments selector


    【解决方案1】:

    您不能将参数传递给您的选择器。既然您正在创建一个按钮,为什么不将按钮标签设置为用户的 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
        }
    }
    

    【讨论】:

    • 好主意它的工作我只会将您的代码编辑为正确的答案谢谢
    • 请记住,如果表格视图支持添加、删除或移动行,则不能使用该行的 indexPath 作为按钮的标记。
    • 确实,这就是我写“用户的id”的原因。
    • 是的。但是tableView不支持行增删,只是为了显示在数据库中找到的用户
    • @KeghamK.,你可以使用 indexPath 但我仍然会推荐用户 ID。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多