Пытается создать приложение, которое сортирует сообщения пользователя «до голосования», как Reddit.Сортировка пользовательских UITableViewCells (Swift 2, Xcode 7)
Был поиск вокруг, пытаясь выяснить, как я могу сортировать свои ячейки по количеству «голосов» (значение Int), которое имеет сообщение.
В диспетчере вида, где отображаются сообщения, я думаю, что большая часть этого релевантна. У меня также есть панель поиска в представлении, которое также играет здесь.
При запуске с приведенным ниже кодом в моем контроллере просмотра ничего не отображается.
Любая помощь будет высоко ценится
import UIKit
import Firebase
class FeedVC: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
var ref: FIRDatabaseReference!
var posts = [Post]()
static var imageCache = NSCache()
var inSearchMode = false
var filteredVenues = [Post]()
var sortByVotes = [Post]()
private var _post: Post?
var post: Post? {
return _post
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
searchBar.delegate = self
searchBar.returnKeyType = UIReturnKeyType.Done
tableView.estimatedRowHeight = 368
ref = FIRDatabase.database().reference()
DataService.ds.REF_POSTS.observeEventType(.Value, withBlock: { snapshot in
print(snapshot.value)
self.sortByVotes = []
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
print("SNAP: \(snap)")
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let post = Post(postKey: key, dictionary: postDict)
self.sortByVotes.append(post)
}
}
}
self.tableView.reloadData()
})
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if inSearchMode {
return filteredVenues.count
}
return sortByVotes.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//let post = posts[indexPath.row]
if let cell = tableView.dequeueReusableCellWithIdentifier("PostCell") as? PostCell {
cell.request?.cancel()
var img: UIImage?
let post: Post!
posts = posts.sort{$0.votes > ($1.votes)} // added this*****
if inSearchMode {
post = filteredVenues[indexPath.row]
} else {
post = sortByVotes[indexPath.row]
}
if let url = post.imageUrl {
img = FeedVC.imageCache.objectForKey(url) as? UIImage
}
cell.configureCell(post, img: img)
return cell
} else {
return PostCell()
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let post = sortByVotes[indexPath.row]
if post.imageUrl == nil {
return 200
} else {
return tableView.estimatedRowHeight
}
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
view.endEditing(true)
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
inSearchMode = false
view.endEditing(true)
posts = posts.sort{$0.votes > ($1.votes)} //added this ***
tableView.reloadData()
} else {
inSearchMode = true
let lower = searchBar.text!.lowercaseString
filteredVenues = sortByVotes.filter({$0.venueName!.rangeOfString(lower) != nil})
tableView.reloadData()
}
}
func sortPosts(){ //removed this function******
sortByVotes = posts.sort { $0.votes > ($1.votes)}
tableView.reloadData()
}
}
вы звоните в 'Func sortPosts()' в любом месте? –
Привет, Виктор, я закончил удаление этой функции и добавил 'posts = posts.sort {$ 0.votes> ($ 1.votes)}' в функции 'textDidChange' и' cellForRowAtIndexPath', см. Выше – ryanbilak
Но работает ли она сейчас ? –