我正在努力实现这一目标,但我的标题中有搜索栏
我正在添加搜索栏作为导航栏的子视图。当我将showScopeBar函数设置为true时,它会保持重叠并显示在搜索栏后面。我试过让导航栏的高度更大但没用。关于如何处理这个问题的任何建议?我不想将我的搜索栏添加到我的集合标题视图中。
import Foundation
import UIKit
import Firebase
import FirebaseDatabase
import FirebaseAuth
class EventSearchController: UICollectionViewController, UISearchBarDelegate, UICollectionViewDelegateFlowLayout{
//resue identifier for the cell that you are constructing
let cellId = "cellID"
//ui search bar that will allow you to type in text and filter out results
//most of the code here is straight forward
//must set delegate to self to get control over certain aspects of search bar
lazy var searchBar: UISearchBar = {
let sb = UISearchBar()
sb.placeholder = "Enter Event"
sb.barTintColor = .gray
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = UIColor.rgb(red: 230, green: 230, blue: 230)
sb.delegate = self
return sb
}()
//detects when search bar text is done editing
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
print("Stopped Editing")
print(searchBar.text)
guard let searchText = searchBar.text else{
return
}
let lowerText = searchText.lowercased()
fetchEvents(searchString: lowerText)
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
{
if searchBar.text?.isEmpty == true
{
filteredEvents.removeAll()
self.collectionView?.reloadData()
}
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
//Changes the first responder to the search bar
searchBar.resignFirstResponder()
}
// this function will detect change in the search bar and filter out the results returned based off what is entered in the search bar
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = .white
navigationController?.navigationBar.addSubview(searchBar)
let navBar = navigationController?.navigationBar
searchBar.anchor(top: navBar?.topAnchor, left: navBar?.leftAnchor, bottom: navBar?.bottomAnchor, right: navBar?.rightAnchor, paddingTop: 0, paddingLeft: 8, paddingBottom: 0, paddingRight: 8, width: 0, height: 0)
//will register a cell to the screen
//notice the EventSearchCell that is one of the parameters
//that is there so it creates the cell in the way that I want it to based off the EventSearchCell Swift File
self.collectionView?.register(EventSearchCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.alwaysBounceVertical = true
collectionView?.keyboardDismissMode = .onDrag
}
//two arrays both of type Event
//one for appending the results of the database search
//one for grabbing the results of the search bar
var filteredEvents = [Event]()
var eventsArray = [Event]()
fileprivate func fetchEvents(searchString: String){
print("Fetching events....")
//create a reference to the location in the database that you want to pull from and observe the value there
let ref = Database.database().reference().child("events")
// this will retur a snapshot with all the data at that location in the database and cast the results as a dictionary for later use
let endString = searchString + "\\uf8ff"
let query = ref.queryOrdered(byChild: "event:name").queryStarting(atValue: searchString).queryEnding(atValue: endString)
print(query)
query.observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String: Any] else{
print(snapshot.value)
return
}
print(snapshot.value)
dictionary.forEach({ (key,value) in
print(key,value)
guard let eventDictionary = value as? [String: Any] else{
return
}
let events = Event(currentEventKey: key, dictionary:eventDictionary)
let filteredEvents = self.eventsArray.filter { (event) -> Bool in
return event.currentEventKey == events.currentEventKey
}
if filteredEvents.count == 0 {
//append
self.eventsArray.append(events)
}
self.filteredEvents = self.eventsArray.filter { (event) -> Bool in
return event.currentEventName.lowercased().contains(searchString.lowercased())
}
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
})
}) { (err) in
print("Failed to fetch event data", err)
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//make sure that the screen is loaded with the proper number of cells when you first go to the screen
return filteredEvents.count
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
searchBar.isHidden = true
searchBar.resignFirstResponder()
let event = filteredEvents[indexPath.item]
print(event.currentEventKey)
let currentEventDetailController = EventDetailViewController()
currentEventDetailController.eventImage = event.currentEventImage
currentEventDetailController.eventName = event.currentEventName
currentEventDetailController.eventDescription = event.currentEventDescription
currentEventDetailController.eventStreet = event.currentEventStreetAddress
currentEventDetailController.eventCity = event.currentEventCity
currentEventDetailController.eventState = event.currentEventState
currentEventDetailController.eventZip = event.currentEventZip
currentEventDetailController.eventKey = event.currentEventKey
self.filteredEvents.removeAll(keepingCapacity: true)
self.eventsArray.removeAll(keepingCapacity: true)
self.collectionView?.reloadData()
navigationController?.pushViewController(currentEventDetailController, animated: true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
searchBar.text = ""
self.collectionView?.reloadData()
filteredEvents.removeAll()
searchBar.isHidden = false
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//creates a cell and cast it as the Appropriate type
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! EventSearchCell
cell.event = filteredEvents[indexPath.row]
return cell
}
//constrols size of the cell
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 66)
}
}