SearchBar没有留在原位(表标题视图) - swift

时间:2016-11-29 10:05:50

标签: ios swift uitableview uisearchbar

我在表格标题视图中创建了一个搜索栏。我实际上不介意在我的导航栏中设置它:navigationItem.titleView = searchController.searchBar ..问题是,当searchBar处于活动状态时,导航栏被解除 - 包括searchBar,所以你看不清楚是什么你在寻找?

我该如何改变?这是我完整的searchBar代码:

import UIKit
import FirebaseDatabase
import FirebaseAuth
import FBSDKCoreKit
import FirebaseStorage

class SearchTableViewController: UITableViewController, UISearchResultsUpdating {


    @IBOutlet var searchUsersTableView: UITableView!


    let searchController = UISearchController(searchResultsController: nil)
    var usersArray = [NSDictionary?]()
    var filteredUsers = [NSDictionary?]()

    let databaseRef = FIRDatabase.database().reference()

    override func viewDidLoad() {
        super.viewDidLoad()

        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        definesPresentationContext = true
        //tableView.tableHeaderView = searchController.searchBar
        navigationItem.titleView = searchController.searchBar
        searchController.searchBar.placeholder = "Søg"
        searchController.searchBar.setValue("Annuller", forKey:"_cancelButtonText")
        let cancelButtonAttributes: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()]
        UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes as? [String : AnyObject], forState: UIControlState.Normal)

        databaseRef.child("UserInformation").queryOrderedByChild("userName").observeEventType(.ChildAdded, withBlock: { (snapshot) in

            self.usersArray.append(snapshot.value as? NSDictionary)


            self.searchUsersTableView.insertRowsAtIndexPaths([NSIndexPath(forRow: self.usersArray.count-1, inSection: 0)], withRowAnimation: .Automatic)


            }) { (error) in
                print(error.localizedDescription)
        }


    }


    override func viewWillAppear(animated: Bool) {
        if let user = FIRAuth.auth()?.currentUser {

            let userId = user.uid

                     FIRDatabase.database().reference().child("Users").child(userId).child("NotificationBadge").observeSingleEventOfType(.Value, withBlock: { (snapshot) in

                // Get user value
                let value = snapshot.value as? NSDictionary
                let badgesNumber = value?["numberOfBadges"] as! Int?



                if badgesNumber != nil {

                    self.tabBarController?.tabBar.items?[3].badgeValue = String(badgesNumber!)

                } else {

                    self.tabBarController?.tabBar.items?[3].badgeValue = nil
                }

                // ...
            }) { (error) in
                print(error.localizedDescription)
            }

        }

    }


    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        tableView.deselectRowAtIndexPath(indexPath, animated: true)

    }


    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showProfile" {
            if let nextVC = segue.destinationViewController as? theProfileTableViewController {
                nextVC.viaSegue = sender! as! String

            }
        }

    }



    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

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

        if searchController.active && searchController.searchBar.text != "" {
            return filteredUsers.count
        }
        return usersArray.count
    }




    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:SearchTableViewCell = tableView.dequeueReusableCellWithIdentifier("searchCell", forIndexPath: indexPath) as! SearchTableViewCell



        let user: NSDictionary?

        if searchController.active && searchController.searchBar.text != "" {
            user = filteredUsers[indexPath.row]
        } else {
            user = self.usersArray[indexPath.row]
        }

        cell.nameLabel.text = user?["userName"] as? String

        let profileUserIDPic = user?["usersUID"] as? String

        let storage = FIRStorage.storage()

        // Refer to your own Firebase storage
        let storageRef = storage.referenceForURL("gs://bigr-1d864.appspot.com")

        let profilePicRef = storageRef.child(profileUserIDPic!+"/profile_pic.jpg")

        // Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
        profilePicRef.dataWithMaxSize(1 * 300 * 300) { (data, error) -> Void in
            if (error != nil) {
                // Uh-oh, an error occurred!
                print("Unable to download image")
                cell.profilePic.image = UIImage(named: "profile.png")
                cell.profilePic.layer.cornerRadius = cell.profilePic.frame.size.width/2
                cell.profilePic.clipsToBounds = true
            } else {
                // Data for "images/island.jpg" is returned
                // ... let islandImage: UIImage! = UIImage(data: data!)
                if (data != nil){
                    cell.profilePic.image = UIImage(data: data!)
                    cell.profilePic.layer.cornerRadius = cell.profilePic.frame.size.width/2
                    cell.profilePic.clipsToBounds = true

                }
            }
        }




        return cell
    }


    func updateSearchResultsForSearchController(searchController: UISearchController) {
        // update something
        filterContent(self.searchController.searchBar.text!)

    }

    func filterContent(searchText: String) {
        self.filteredUsers = self.usersArray.filter{ user in
            let username = user!["userName"] as? String

            return (username?.lowercaseString.containsString(searchText.lowercaseString))!
        }
        self.tableView.reloadData()
    }


}

当进入搜索页面时,它看起来像这样(因为我添加了插图 enter image description here

搜索用户时,它看起来像这样 enter image description here

点击用户并返回搜索时,它看起来像这样 enter image description here

0 个答案:

没有答案