首页 > 解决方案 > 选择具有两个按钮的表视图时更新数组时出错

问题描述

我有一个带有两个按钮和一个标签的表格视图,我想根据我选择的按钮将标签中的文本保存在两个不同的数组中。

| _添加按钮_______标签______________收藏按钮___| | _添加按钮_______标签______________收藏按钮___|

当我选择添加按钮时,我希望将标签保存在添加按钮数组中,当我选择收藏按钮时,我想将文本保存在收藏夹中。

我在下面执行的代码适用于添加按钮,但始终存储收藏按钮的第一个单元格。我在这里想念什么?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SegmentControlCell
        cell.addPointsLabel.text? = SegmentNetworkCallObj.AFResponse[indexPath.row]["Description"] as? String ?? ""
        cell.addTaskButton.tag = indexPath.row
        cell.addTaskButton.addTarget(self, action: #selector(addButtontapped(_:)), for: .touchUpInside)
        cell.addTaskButton.addTarget(self, action: #selector(favouriteButtonTapped(_:)), for: .touchUpInside)
            return cell
        }

//Button Selection
@IBAction func addButtontapped(_ sender: Any) {
        let selectedTask = SegmentNetworkCallObj.AFResponse[(sender as AnyObject).tag]["Description"]
        dailyDeedsArray.append(selectedTask as! String)
        print("addbutton",dailyDeedsArray)
}

    @IBAction func favouriteButtonTapped(_ sender: Any) {
        let selectedTask = SegmentNetworkCallObj.AFResponse[(sender as AnyObject).tag]["Description"]
        favouritesArray.append(selectedTask as! String)
        print("favourites",favouritesArray)

    }

标签: iosswift

解决方案


似乎每个单元格中有 2 个按钮,一个被调用addTaskButton,另一个可能被调用或类似的东西,但您只在委托方法中addFavoriteButton分配和更新标签值,这对于您的收藏夹按钮来说是一个问题,因为您在这两种方法中都可以访问. 此外,您为 分配了 2 个不同的目标,我想这是一个错误。addTaskButtontableView(sender as AnyObject).tagIBActionaddTaskButton

我认为代码应该是这样的:

cell.addTaskButton.tag = indexPath.row
cell.addTaskButton.addTarget(self, action: #selector(addButtontapped(_:)), for: .touchUpInside)

cell.addFavoriteButton.tag = indexPath.row
cell.addFavoriteButton.addTarget(self, action: #selector(favouriteButtonTapped(_:)), for: .touchUpInside)

推荐阅读