我有一个带有两个按钮和一个标签的表格 View ,我想根据我选择的按钮将标签中的文本保存在两个不同的数组中。
| _添加按钮_______标签________收藏夹按钮___| | _添加按钮________标签________收藏夹按钮___|
当我选择添加按钮时,我希望将标签保存在添加按钮数组中,而当我选择收藏按钮时,我希望将文本保存在收藏夹中。
我在下面做的代码对于添加按钮工作正常,但总是存储最喜欢的按钮的第一个单元格。我在这里缺少什么?
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)
}
最佳答案
似乎每个单元格中有 2 个按钮,一个称为 addTaskButton
,另一个可能称为 addFavoriteButton
或类似的东西,但您只分配和更新标记值tableView
委托(delegate)方法中的 addTaskButton
,这对您的收藏夹按钮来说是个问题,因为您在两个 中访问
方法。此外,您为 (sender as AnyObject).tag
>IBActionaddTaskButton
分配了 2 个不同的目标,我猜这是一个错误。
我认为代码应该是这样的:
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)
关于ios - 选择具有两个按钮的 TableView 时更新数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57825416/