Swift 当表格中的行数超过7行时,多个TableViewCell上的背景颜色会发生变化

Swift 当表格中的行数超过7行时,多个TableViewCell上的背景颜色会发生变化,swift,uitableview,tableview,Swift,Uitableview,Tableview,我正在从Firebase读取数据,然后在tableview单元格中显示这些数据。还有一个本地存储的文件,其中包含每个单元格的已读/未读状态。该文件包含Firebase中每个子级的密钥,我将其和每个单元格中的数据进行匹配 基本上,如果单元格中有一个在文件中也可以找到的键,则该数据被认为是用户“读取”的。但是,如果单元格的密钥在本地文件中没有等效项,则该数据被视为“未读” 到目前为止,这是完美的。然后,我为每个单元格添加了两个滑动功能。首先标记为已读,也标记为未读。当标记为“读取”时,滑动调用一个函

我正在从Firebase读取数据,然后在tableview单元格中显示这些数据。还有一个本地存储的文件,其中包含每个单元格的已读/未读状态。该文件包含Firebase中每个子级的密钥,我将其和每个单元格中的数据进行匹配

基本上,如果单元格中有一个在文件中也可以找到的键,则该数据被认为是用户“读取”的。但是,如果单元格的密钥在本地文件中没有等效项,则该数据被视为“未读”

到目前为止,这是完美的。然后,我为每个单元格添加了两个滑动功能。首先标记为已读,也标记为未读。当标记为“读取”时,滑动调用一个函数,将单元格的密钥写入本地文件。相反,当标记为“未读”时,滑动调用另一个函数,从本地文件中删除密钥。这也非常有效

但是,在刷卡时,我还必须更改单元格背景颜色以反映“已读”或“未读”。这会导致一个问题,因为单元格会重新加载以供重用。。。在我的例子中,在它重新加载之前,我得到了7个单元格

这意味着,如果我有7个以上的单元格,并且我将某些内容标记为“已读”,那么我最终会更改多个单元格的背景颜色。写文件的东西很好用。。。只复制了背景色

我在editActionsForRowAt函数中更改颜色,如下所示:

    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

    let Action2 = UITableViewRowAction(style: .default, title: "Mark Read", handler: { (action, indexPath) in
//函数在设置颜色之前继续执行操作

    if filteredMessageIDforSwipe.count == 0  {

    let selectedCell = self.Nomination2TableView.cellForRow(at: indexPath) as! Nomination2TableViewCell

    selectedCell.contentView.backgroundColor = UIColor(hexString: "#ffffff")
请注意,我没有选择单元格。。。而是刷卡,然后尝试更改所刷卡单元格的单元格背景颜色

显然,我只想让我刷过的电池改变颜色,而不是另一个电池(如果我有7个以上的电池)

谢谢

N

编辑:我已经按照下面的建议修改了editActionsForRowAt,但没有效果

    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

    selectedRowIndexForReadUnread = indexPath.row

    let Action2 = UITableViewRowAction(style: .default, title: "Mark Read", handler: { (action, indexPath) in

    if filteredMessageIDforSwipe.count == 0 && selectedRowIndexForReadUnread = indexPath.row   {

    let selectedCell = self.Nomination2TableView.cellForRow(at: indexPath) as! Nomination2TableViewCell

    selectedCell.contentView.backgroundColor = UIColor(hexString: "#ffffff")
编辑:以下是editActionsForRowAt函数供参考。。。行动2和行动5是相关的

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

    selectedRowIndexForReadUnread = indexPath.row

    if tableView == self.Nomination2SearchTableView {


        let Action1 = UITableViewRowAction(style: .default, title: "Select", handler: { (action, indexPath) in

            self.Nomination2SearchTableView.isHidden = true
            self.Nomination2TableView.isHidden = false
            NominationState = "Active"

            let SearchObject: Nomination2SearchModel
            SearchObject = Nomination2SearchList[indexPath.row]

            userIDStringforNominationSearch = SearchObject.UserIDString!
            let FullName = SearchObject.Full_Name

            self.FullNameLabel.isHidden = false
            self.FullNameLabel.text = "Showing " + FullName! + "'s Shout Outs"

            self.LoadDataFromNominationafterSearch()
            self.ActiveButton.setTitleColor(.orange, for: .normal)


            let banner = NotificationBanner(title: "Tip", subtitle: "Swipe to select a user.", style: .info)
            banner.haptic = .none
            banner.show()

            //We are setting the editor mode to the opposite of what is displayed in the tableview, because EditorMode text is what is displayed when you swipe the cell.
           // EditorMode = "Set to Complete"

        })
        return [Action1]

    }

    if tableView == self.Nomination2TableView{


        if NominationState == "Active" {


                     let Action2 = UITableViewRowAction(style: .default, title: "Mark Read", handler: { (action, indexPath) in

                        let searchObject9: Nomination2Model
                        searchObject9 = Nomination2List[indexPath.row]
                        let messageIDKey = searchObject9.key


                        let filename = self.getDocumentsDirectory().appendingPathComponent("output.txt")
                        do {

                            let textStringFromFile = try String(contentsOf: filename, encoding: .utf8)

                            var result: [(messageID: String, readStatus: String)] = []

                            // var indexCount = result.count

                            let rows = textStringFromFile.components(separatedBy: "\n")
                            for row in rows {
                                let columns = row.components(separatedBy: ",")
                                result.append((columns[0], columns[1]))
                            }

                            filteredMessageIDforSwipe = result.filter { $0.messageID == (messageIDKey) }

                        }
                        catch{

                        }

                        if filteredMessageIDforSwipe.count == 0   {

                        let selectedCell = self.Nomination2TableView.cellForRow(at: indexPath) as! Nomination2TableViewCell
                            // let selectedCellForReadMessages:UITableViewCell = self.Nomination2TableView.cellForRow(at: indexPath)! as! Nomination2TableViewCell
                        selectedCell.contentView.backgroundColor = UIColor(hexString: "#ffffff")

                        // let myReadCell = self.Nomination2TableView.cellForRow(at: indexPath) as! Nomination2TableViewCell
                        // myReadCell.NominationNameLabel.textColor = UIColor.lightGray
                        // myReadCell.NominationTextLabel.textColor = UIColor.lightGray

                        let NominationObject: Nomination2Model
                        NominationObject = Nomination2List[indexPath.row]
                        nominationKeyForWhenCellSelected = NominationObject.key
                        self.writeFile()
                        // self.removeRowFromFile()
                        }

                        if filteredMessageIDforSwipe.count > 0 {

                            let alert = UIAlertController(title: "Failure",
                                                          message: "Shout-out is already read!",
                                                          preferredStyle: .alert)
                            alert.addAction(UIAlertAction(title: "OK", style: .default))
                            self.present(alert, animated: true, completion: nil)

                        }

            })



            let Action5 = UITableViewRowAction(style: .default, title: "Mark Unread", handler: { (action, indexPath) in

                let searchObject9: Nomination2Model
                searchObject9 = Nomination2List[indexPath.row]
                let messageIDKey = searchObject9.key


                let filename = self.getDocumentsDirectory().appendingPathComponent("output.txt")
                do {

                    let textStringFromFile = try String(contentsOf: filename, encoding: .utf8)

                    var result: [(messageID: String, readStatus: String)] = []

                    // var indexCount = result.count

                    let rows = textStringFromFile.components(separatedBy: "\n")
                    for row in rows {
                        let columns = row.components(separatedBy: ",")
                        result.append((columns[0], columns[1]))
                    }




                    filteredMessageIDforSwipe = result.filter { $0.messageID == (messageIDKey) }

                }
                catch{

                }

                if filteredMessageIDforSwipe.count > 0 {


                    let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
                    selectedCell.contentView.backgroundColor = UIColor(hexString: "#fcf0e5")

                    // let myCell = self.Nomination2TableView.cellForRow(at: indexPath) as! Nomination2TableViewCell
                    // myCell.NominationNameLabel.textColor = UIColor.orange
                    // myCell.NominationTextLabel.textColor = UIColor.black

                    let NominationObject: Nomination2Model
                    NominationObject = Nomination2List[indexPath.row]
                    nominationKeyForWhenCellSelected = NominationObject.key
                    // self.writeFile()
                    self.removeRowFromFile()
                }

                if filteredMessageIDforSwipe.count == 0 {

                    let alert = UIAlertController(title: "Failure",
                                                  message: "Shout-out is already unread!",
                                                  preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .default))
                    self.present(alert, animated: true, completion: nil)

                }

            })

            Action2.backgroundColor = UIColor.lightGray
            Action5.backgroundColor = UIColor.blue
            return[Action2, Action5]
        }



     if NominationState == "Approve"{

     let Action3 = UITableViewRowAction(style: .default, title: NominationState, handler: { (action, indexPath) in


            let searchObject9: Nomination2Model
            searchObject9 = Nomination2List[indexPath.row]

            ForName  = searchObject9.ForName!
            FromName = searchObject9.FromName!
            ForWhat = searchObject9.ForWhat!
             key = searchObject9.key!
             ForUserID = searchObject9.ForUserID!
             FromUserID = searchObject9.FromUserID!
             PointsGifted = searchObject9.PointsGifted!
             NominationText = searchObject9.NominationText!
            ImageNameNominations = searchObject9.ImageNameString!
            ImageURLNominations = searchObject9.ImageURL!


            databaseReference = Database.database().reference()

            databaseReference.child("Users").child(FromUserID).observeSingleEvent(of: DataEventType.value, with: { (snapshot) in

                let value = snapshot.value as? NSDictionary

                let CurrentPointsRedeemed = value?["Points_Redeemed"] as? Int
                let CurrentPointsBalance = value? ["Points_Balance"] as? Int

                let NewPointsRedeemed = CurrentPointsRedeemed! + PointsGifted

                let NewPointsBalance = CurrentPointsBalance! - PointsGifted



                if NewPointsBalance >= 0{

                    databaseReference.child("Users").child(FromUserID).updateChildValues(["Points_Redeemed": NewPointsRedeemed])

                    databaseReference.child("Users").child(FromUserID).updateChildValues(["Points_Balance": NewPointsBalance])



                    self.postToFirebase()
                    self.giftPoints()
                    self.pendingCount()

                    Nomination2List.remove(at: indexPath.row)
                    tableView.deleteRows(at: [indexPath], with: .fade)

                }

                if NewPointsBalance <= 0{

                    let alert = UIAlertController(title: "Nominations",
                                                  message: "Not Enough Points for approval",
                                                  preferredStyle: .alert)

                    alert.addAction(UIAlertAction(title: "OK", style: .default))

                    self.present(alert, animated: true, completion: nil)


                }

        })


     })

        Action3.backgroundColor = UIColor.blue
        return[Action3]

        }
        //here

        //Action2.backgroundColor = UIColor.blue
        //return[Action2]
     else{
        return [UITableViewRowAction]()
        }
    }
    else {
        return [UITableViewRowAction]()
    }

}
func tableView(tableView:UITableView,editActionsForRowAt indexath:indexPath)->[UITableViewRowAction]?{
selectedRowIndexForReadUnread=indexPath.row
如果tableView==self.namignation2SearchTableView{
让Action1=UITableViewRowAction(样式:。默认值,标题:“选择”,处理程序:{(操作,索引XPath)在
self.namignation2searchtableview.ishiden=true
self.namignation2tableview.ishiden=false
提名状态=“活动”
让SearchObject:Nagnation2SearchModel
SearchObject=Nagnation2Searchlist[indexPath.row]
userIDStringforNominationSearch=SearchObject.UserIDString!
让FullName=SearchObject.Full\u Name
self.fullnamelab.ishiden=false
self.fullnamelab.text=“显示“+FullName!+”的呼喊声”
self.loaddatafromnegationaftersearch()的
self.ActiveButton.setTitleColor(.orange,表示:.normal)
let banner=NotificationBanner(标题:“提示”,副标题:“滑动以选择用户”,样式:.info)
banner.haptic=.none
banner.show()
//我们将编辑器模式设置为与tableview中显示的相反的模式,因为当您滑动单元格时,会显示EditorMode文本。
//EditorMode=“设置为完成”
})
返回[行动1]
}
如果tableView==self.namignation2tableview{
如果提名状态==“活动”{
让Action2=UITableViewRowAction(样式:。默认值,标题:“标记读取”,处理程序:{(操作,索引XPath)在
让searchObject9:提名2模型
searchObject9=Nagnation2List[indexPath.row]
让messageIDKey=searchObject9.key
让filename=self.getDocumentsDirectory().appendingPathComponent(“output.txt”)
做{
让textStringFromFile=try String(内容:文件名,编码:.utf8)
变量结果:[(messageID:String,readStatus:String)]=[]
//var indexCount=result.count
让rows=textStringFromFile.components(以“\n”分隔)
一行一行{
让columns=row.components(以“,”分隔)
追加((列[0],列[1]))
}
filteredMessageIDforSwipe=result.filter{$0.messageID==(messageIDKey)}
}
抓住{
}
如果filteredMessageIDforSwipe.count==0{
让selectedCell=self.Nagnation2TableView.cellForRow(at:indexPath)作为!Nagnation2TableViewCell
//让selectedCellForReadMessages:UITableViewCell=self.Namination2TableView.cellForRow(at:indexPath)!as!Namination2TableViewCell
selectedCell.contentView.backgroundColor=UIColor(十六进制字符串:“#ffffff”)
//让myReadCell=self.Nagnation2TableView.cellForRow(at:indexPath)作为!Nagnation2TableViewCell
//myReadCell.NaminationNameLabel.textColor=UIColor.lightGray
//myReadCell.NaminationTextLabel.textColor=UIColor.lightGray
让提名对象:提名2模型
提名对象=提名2List[indexPath.row]
NagnitionKeyforWhencellSelected=NagnitionObject.key
self.writeFile()
//self.removowfromfile()
}
如果FilteredMessageForSwipe.count>0{
let alert=UIAlertController(tit
    let backgroundView = UIView()
    backgroundView.backgroundColor = UIColor(red:0.94, green:0.94, blue:0.94, alpha:1.0)
    cell.selectedBackgroundView = backgroundView
let selectedCell = self.Nomination2TableView.cellForRow(at: indexPath) as! Nomination2TableViewCell

if filteredMessageIDforSwipe.count == 0  {

selectedCell.contentView.backgroundColor = UIColor(hexString: "#ffffff")
} else {
selectedCell.contentView.backgroundColor = UIColor.white 
//or whatever the color of the background is by default
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

let userDefaults = UserDefaults.standard

let testArray = ["Test1", "Test2", "Test3", "Test4", "Test5", "Test6", "Test7", "Test8", "Test9", "Test10", "Test11", "Test12", "Test13", "Test14", "Test15", "Test16", "Test17", "Test18", "Test19", "Test20"]

var selectedCellIndexPaths = [Int]()

override func viewDidLoad() {
    super.viewDidLoad()
    
    tableView.delegate = self
    tableView.dataSource = self
    if let values = userDefaults.value(forKey: "IndexPathsArray") as? Array<Int> {
    selectedCellIndexPaths = values
    }
    print("selected", selectedCellIndexPaths)
    
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return testArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    
    cell.textLabel?.text = testArray[indexPath.row]
    
    cell.backgroundColor = UIColor.white
    
    for indx in selectedCellIndexPaths {
        if indexPath.row == indx {
            cell.backgroundColor = UIColor.red
        }
    }
    
    return cell
}

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    
            let cell = tableView.cellForRow(at: indexPath)
    
    let action = UITableViewRowAction(style: .default, title: "Mark Read") { (action, indexPath) in
        
        cell?.backgroundColor = UIColor.red
        
        self.selectedCellIndexPaths.append(indexPath.row)
        
        self.userDefaults.set(self.selectedCellIndexPaths, forKey: "IndexPathsArray")
        print(self.selectedCellIndexPaths)
    }
    
    return [action]
    
}
var selectedIndexPath: [IndexPath]?

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedIndexPath.append(indexPath)
tableView.reloadData()}

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.contentView.backgroundColor = selectedIndexPath?.contains(indexPath) ? UIColor(hexString: "#efefef") :  UIColor.clear}
var selectedRowIndex:Int = -1

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {       
        let cell = self.Nomination2TableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as Nomination2TableViewCell!
        if self.selectedRowIndex == indexPath.row {
            cell.contentView.backgroundColor = UIColor(hexString: "#efefef")
        } else {
            cell.contentView.backgroundColor = UIColor(hexString:"defaultColor")
        }    
        return cell
    }

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.selectedRowIndex = indexPath.row            
        self.Nomination2TableView.reloadRows(at:[indexPath], with: .none)
    }
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
DispatchQueue.main.async {
    self.Nomination2TableView.beginUpdates()    
    self.selectedRowIndex = indexPath.row            
    self.Nomination2TableView.reloadRows(at:[indexPath], with: .none)
    self.Nomination2TableView.endUpdates()      
}

    let Action2 = UITableViewRowAction(style: .default, title: "Mark Read", handler: { (action, indexPath) in
override func prepareForReuse() {
    // set the color to default
}