我有一個UITableViewCell內的UIButton,其中圖像更改一旦按鈕被點擊。儘管所選按鈕可以按照預期進行選擇,但一旦UITableView滾動,所選圖像就會消失,因爲這些單元格會被重新使用。UITableViewCell圖像滾動時消失
我在編寫邏輯時遇到了麻煩。請幫忙。
我的代碼是下面,在夫特3.
CellForRow:
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)
}
}
}
不要多次提問相同的問題。 https://stackoverflow.com/questions/45627323/selected-button-of-a-uitableviewcell-get-disappear-when-scrolling/45629235#45629235 – PGDev
[滾動時,UITableViewCell的選定按鈕會消失]的可能重複(https ://stackoverflow.com/questions/45627323/selected-button-of-a-uitableviewcell-get-disappear-when-scrolling) – PGDev