swift - 当表格中的行数超过 7 行时,多个表格 View 单元格的背景颜色会发生变化

标签 swift uitableview tableview

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

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

到目前为止,一切正常。然后我为每个单元格添加了两个滑动功能。先标记为已读,再标记为未读。当标记为“已读”时,滑动会调用一个函数,将单元格的键写入本地文件。相反,当标记为“未读”时,滑动会调用另一个从本地文件中删除 key 的函数。这也很完美。

但是,在滑动时,我还必须更改单元格背景颜色以反射(reflect)“已读”或“未读”。这导致了一个问题,因为单元格被重新加载以供重用......在我的例子中,我在重新加载之前得到了 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 函数...Action2 和 Action5 是相关的。

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]()
    }

}

最佳答案

表格 View 单元格得到重用,这就是其他单元格的背景颜色发生变化的原因。

hacking with swift 上有一段不错的代码片段这正是你需要的。我也在我自己的项目中使用这个片段。

所以在你的情况下它看起来像这样:

    let backgroundView = UIView()
    backgroundView.backgroundColor = UIColor(red:0.94, green:0.94, blue:0.94, alpha:1.0)
    cell.selectedBackgroundView = backgroundView

用这个替换你的代码,我认为它会没问题。希望这会有所帮助。

编辑:

要仅更改滑动单元格的颜色,您可以尝试在 if 语句之后插入一个 else 语句。你可以试试这个:

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
}

如果这不能解决问题,请告诉我!

编辑 2:

我在一个(过于简化的)小测试应用程序中重新创建了您问题的核心。回顾一下,这就是我所理解的问题的核心:您想设置在表格 View 中滑动的单元格的颜色。您还希望它们在您重新打开应用程序时保持该颜色,并防止其他单元格因单元格重复使用而变色。

在下面的解决方案中,我没有使用与您使用的完全相同的对象和变量,因为如果没有您的完整代码,将很难重新创建这些对象和变量。相反,这是您可以在自己的解决方案中实现的逻辑。因此,您似乎将选定的单元格 indexPaths 保留在 filteredMessageIDforSwipe 中 - 因此您应该遍历该数组并为具有相应索引路径的单元格设置颜色。在调用 for 循环之前设置默认单元格背景颜色很重要。

这是我的示例 ViewController:

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]
    
}

如果您需要进一步的帮助,请告诉我!

关于swift - 当表格中的行数超过 7 行时,多个表格 View 单元格的背景颜色会发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54418311/

相关文章:

ios - 清除数据源,重新加载数据,单元格仍然有旧信息?

ios - 如何隐藏我的 UITableViewCell 之外的内容

ios - 将 IBOutlets 连接到 UITableViewCell 原型(prototype)

JavaFX如何从Tableview中获取选定行的数据

Swift 尝试为同一索引路径使多个单元格出队,这是不允许的

ios - swift 中的静态字典类型变量声明?

ios - Swift - 即使控件可见, View 也不显示/更新控件

java - 表格行选择后可以取消选择吗?

Xcode 7/swift 2.0 XCTestCase waitForExpectationsWithTimeout() EXC_BAD_ACCESS

swift - 在 swift 中比 double 更精确