我在UITableViewCell中有一个UIButton,一旦按下按钮,图像就会改变。虽然所选按钮按预期选择,但一旦UITableView滚动,所选图像就会消失,因为细胞会被重复使用。
我在编写逻辑时遇到了麻烦。请帮忙。
我的代码如下,在Swift 3中。
CellForRow:
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)
}
}
}
点击功能:
SELECT TABLE_NAME, CONSTRAINT_NAME FROM USER_CONSTRAINTS
WHERE R_OWNER = 'OWNERNAME' AND STATUS ='ENABLED' AND CONSTRAINT_TYPE = 'R'
AND R_CONSTRAINT_NAME IN ( SELECT CONSTRAINT_NAME FROM ALL_CONSTRAINTS
WHERE CONSTRAINT_TYPE IN ('P', 'U') AND TABLE_NAME = 'REGIONS'
AND OWNER = 'OWNERNAME' )
答案 0 :(得分:1)
您需要有一个数组,用于存储选择的索引,例如您拥有的selectedSongList数组。然后在你的cellForRow方法中你需要使用来自这个数组的bool proparty给你的按钮选择或取消选择状态,或者在你的addSongButtonIdentifier方法中选择状态需要
addButton.isSelected = selectedSongList.contains(indexPath.row)
答案 1 :(得分:1)
创建一个Model类来填充UITableView并在该模型中获取UIImage varaivals,它将保存单元格的当前图像。单击按钮操作时,只需使用当前图像更改UIImage变量。