【发布时间】:2017-08-11 05:04:39
【问题描述】:
我正在处理一个用 swift 3 编码的项目,我在 UITableViewCell 中有一个 UIButton,一旦点击按钮,图像就会发生变化。尽管选定的按钮按预期被选中,但一旦 UITableview 滚动,选定的图像就会消失,因为单元格被重复使用。因为我是编程新手,在编写逻辑时遇到了麻烦。帮助将非常感谢下面的代码。
CellFow
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
//Button_Action
addSongButtonIdentifier(cell: cell, indexPath.row)
}
这是创建单元格的地方。
func addSongButtonIdentifier(cell: UITableViewCell, _ index: Int) {
let addButton = cell.viewWithTag(TABLE_CELL_TAGS.addButton) as! UIButton
//accessibilityIdentifier is used to identify a particular element which takes an input parameter of a string
//assigning the indexpath button
addButton.accessibilityIdentifier = String (index)
// print("visible Index:",index)
print("Index when scrolling :",addButton.accessibilityIdentifier!)
addButton.setImage(UIImage(named: "correct"), for: UIControlState.selected)
addButton.setImage(UIImage(named: "add_btn"), for: UIControlState.normal)
addButton.isSelected = false
addButton.addTarget(self, action: #selector(AddToPlaylistViewController.tapFunction), for:.touchUpInside)
}
点击功能
func tapFunction(sender: UIButton) {
print("IndexOfRow :",sender.accessibilityIdentifier!)
// if let seporated by a comma defines, if let inside a if let. So if the first fails it wont come to second if let
if let rowIndexString = sender.accessibilityIdentifier, let rowIndex = Int(rowIndexString) {
self.sateOfNewSongArray[rowIndex] = !self.sateOfNewSongArray[rowIndex]//toggle the state when tapped multiple times
}
sender.isSelected = !sender.isSelected //image toggle
print(" Array Data: ", self.sateOfNewSongArray)
selectedSongList.removeAll()
for (index, element) in self.sateOfNewSongArray.enumerated() {
if element{
print("true:", index)
selectedSongList.append(songDetailsArray[index])
print("selectedSongList :",selectedSongList)
}
}
}
【问题讨论】:
-
一旦 tableview 重新加载,您的选择就会消失,因为您需要将选定状态存储在数据集中而不是按钮状态
-
您需要存储选中项的索引或行号。
-
我知道原因,但编写逻辑有困难,代码 sn-p 将不胜感激
标签: ios swift uitableview swift3