Tableview搜索栏没有正确返回detailTextLabel(Xcode - Swift)

时间:2017-12-14 03:38:26

标签: ios swift uitableview firebase

我对Xcode很陌生,所以我对搜索栏和表格不太了解。截至目前,搜索栏正常工作,只是在搜索时没有返回特定展位的正确值。请查看图像以便于参考。非常感谢您的帮助。谢谢!

import UIKit
import FirebaseDatabase

var ref: DatabaseReference?
var databaseHandle: DatabaseHandle?
var postData = [String]()
var postData2 = [String]()
var currentpostDataArray = [String]()
var tableDataArray = [tableData]()

class TableViewController: UITableViewController, UISearchBarDelegate {


    @IBOutlet var searchBar: UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpSearchBar()


        ref = Database.database().reference() //set the firebase reference

        // Retrieve the post and listen for changes
        databaseHandle = ref?.child("Posts2").observe(.value, with: { (snapshot) in
            // Code to execute when a child is added under "Posts"
            postData.removeAll()
            postData2.removeAll()
            tableDataArray.removeAll()

            for child in snapshot.children {
                let snap = child as! DataSnapshot
                let key = snap.key
                let value = String(describing: snap.value!)
                let rating = (value as NSString).integerValue

                postData.append(key)
                postData2.append(value)

                tableDataArray.append(tableData(boothName: key, boothRating: rating))
                currentpostDataArray = postData
            }

            self.tableView.reloadData()


        })

    }


    private func setUpSearchBar() {
        searchBar.delegate = self
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return currentpostDataArray.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = currentpostDataArray[indexPath.row]
        cell.detailTextLabel?.text = postData2[indexPath.row] + " ♥"
        cell.detailTextLabel?.textColor = UIColor.red;
        return cell
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        currentpostDataArray = postData.filter({ (postdata) -> Bool in
            switch searchBar.selectedScopeButtonIndex {
            case 0:
                if searchText.isEmpty { return true }
                return postdata.lowercased().contains(searchText.lowercased())
            case 1:
                if searchText.isEmpty { return true }
                return postdata.lowercased().contains(searchText.lowercased())
            default:
                return false
            }
        })
        tableView.reloadData()
    }


        func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
            switch selectedScope {
            case 0:
                currentpostDataArray.removeAll()
                postData2.removeAll()
                for data in tableDataArray {
                    currentpostDataArray.append(data.boothName)

                    let value = String(describing: data.boothRating)
                    postData2.append(value)
                }
                self.tableView.reloadData()

            case 1:
                currentpostDataArray.removeAll()
                postData2.removeAll()
                let sortedTableData = tableDataArray.sorted(by: { $0.boothRating > $1.boothRating })
                for data in sortedTableData {
                    currentpostDataArray.append(data.boothName)

                    let value = String(describing: data.boothRating)
                    postData2.append(value)
                }
                self.tableView.reloadData()

            default:
                break

            }
            tableView.reloadData()
        }

}

class tableData {
    var boothName: String
    var boothRating: Int
    init(boothName: String, boothRating: Int) {
        self.boothName = boothName
        self.boothRating = boothRating
    }
}

enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

这种情况正在发生,因为在您的代码中,postData包含密钥。

 for child in snapshot.children {
            let snap = child as! DataSnapshot
            let key = snap.key
            let value = String(describing: snap.value!)
            let rating = (value as NSString).integerValue

            ***postData.append(key)***

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)

您将返回包含密钥无值的发布日期内容。这里你没有更新postData2。

<强>因此

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text = currentpostDataArray[indexPath.row]
    cell.detailTextLabel?.text = postData2[indexPath.row] + " ♥" 
    cell.detailTextLabel?.textColor = UIColor.red;
    return cell
}

cell.detailTextLabel?.text采用postData2的旧值。因为在postData2中第一个索引值是38。

我想你明白了。

<强>解决方案:

永远不要创建两个数组来处理数据。您可以创建一个字典数组来处理数据。在你的情况下,它是currentpostDataArray和postData2。

我将使用单个字典数组修改代码。

override func viewDidLoad() {
    super.viewDidLoad()

    setUpSearchBar()


    ref = Database.database().reference() //set the firebase reference

    // Retrieve the post and listen for changes
    databaseHandle = ref?.child("Posts2").observe(.value, with: { (snapshot) in
        // Code to execute when a child is added under "Posts"
        postData.removeAll()
        postData2.removeAll()
        tableDataArray.removeAll()

        for child in snapshot.children {
            let snap = child as! DataSnapshot
            let key = snap.key
            let value = String(describing: snap.value!)
            let rating = (value as NSString).integerValue

            postData.append(key)
            postData2.append(value)

            tableDataArray.append(tableData(boothName: key, boothRating: rating))
            currentpostDataArray = tableDataArray
        }

        self.tableView.reloadData()


    })

}

 // cellForRowAtIndexpath

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text = currentpostDataArray[indexPath.row]. boothName
    cell.detailTextLabel?.text = currentpostDataArray[indexPath.row]. boothRating + " ♥"
    cell.detailTextLabel?.textColor = UIColor.red;
    return cell
}

//searchBar delegate

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    currentpostDataArray = tableDataArray
    for item in tableDataArray {
        let str = item.boothName
        if str.lowercased().range(of: searchText) != nil {
            currentpostDataArray.append(item)
        }
    }


    tableView.reloadData()
}