我正在尝试搜索解析数据库并将结果显示在集合视图中。故事板上的所有连接都是正确的。单击搜索按钮时,键盘不会消失,程序不会尝试搜索数据库,也不会使用搜索到的信息更新单元格。我该如何解决这个问题?
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var collectionview: UICollectionView!
var users = [PFObject]()
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
}
func loadUsers(){
var query = PFQuery(className:"_User")
if searchBar.text != ""{
query.whereKey("username", containsString: searchBar.text)
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
// The find succeeded now process the found objects into the countries array
if error == nil {
// Clear existing country data
self.users.removeAll(keepCapacity: true)
// Add country objects to our array
if let objects = objects as? [PFObject] {
self.users = Array(objects.generate())
}
// reload our data into the collection view
self.collectionview.reloadData()
print(self.users)
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return users.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionview.dequeueReusableCellWithReuseIdentifier("searchcell", forIndexPath: indexPath) as! searchcustomcell
if let value = users[indexPath.item]["username"] as? String{
cell.searchname.text = value
}
if let value = users[indexPath.item]["ProPic"] as? PFFile{
let finalImage = users[indexPath.item][""] as? PFFile
finalImage!.getDataInBackgroundWithBlock(){
(imageData: NSData?, error: NSError?) -> Void in
if error == nil{
if let imageData = imageData{
cell.searchimage.image = UIImage(data: imageData)
}
}
}
}
print(users)
return cell
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
// Dismiss the keyboard
searchBar.resignFirstResponder()
// Reload of table data
self.loadUsers()
print(users)
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
// Clear any search criteria
searchBar.text = ""
// Dismiss the keyboard
searchBar.resignFirstResponder()
// Reload of table data
self.loadUsers()
}
答案 0 :(得分:1)
searchBarTextDidEndEditing
未被调用。你需要使用:
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
self.loadUsers()
print(users)
}