【发布时间】:2016-05-30 22:11:35
【问题描述】:
我在重新加载 tableView 时遇到问题。当我的firebaseService.getAllPosts() 方法运行时,它会给我数据库中的两个帖子(如预期的那样)。我可以这么说,因为当didSet 打印运行时,它给了我正确的计数。但是,因为我知道在方法运行之前设置了 tableview,所以我知道我需要重新加载 tableview 以更新数据源中的计数。问题就在于此。我故意将posts 变量放在我的班级之外,以便可以从每个班级访问它。 (如果这不是一个好的做法,请告诉我。)
我在哪里可以运行 tableView.reloadData() 以便我的 tableView 数据源更新并为我提供 posts 的正确功能?我尝试将FeedController().tableView.reloadData() 放入didSet 并尝试将其放入viewDidLoad(),但这些都不起作用。我还尝试添加一个名为_posts 的变量并将其设置为等于posts,然后在didSet 中添加didSet 和tableView.reloadData(),但这也不起作用。
class FeedController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView = UITableView(frame: UIScreen.mainScreen().bounds, style: UITableViewStyle.Plain)
let cellId = "PhotoCell"
let textCellId = "TextCell"
let firebaseService = FirebaseService.sharedInstance
static let sharedFeedInstance = FeedController()
var posts = [Post]() {
didSet {
tableView.reloadData()
print(posts.count)
}
}
override func viewDidLoad() {
super.viewDidLoad()
firebaseService.getAllPosts()
tableView.dataSource = self
tableView.delegate = self
self.view.addSubview(tableView)
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
print("sections: \(posts.count)")
return posts.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let post:Post? = posts[indexPath.section]
if let _ = post?.imageContentName {
let photoFeedCell = tableView.dequeueReusableCellWithIdentifier(self.cellId, forIndexPath: indexPath) as? FeedTVCellWithPhoto
photoFeedCell?.post = post
return photoFeedCell!
}
let textFeedCell = tableView.dequeueReusableCellWithIdentifier(self.textCellId, forIndexPath: indexPath) as? FeedTVCellText
textFeedCell?.post = post
return textFeedCell!
}
}
更新 1:FirebaseService 类中的 getAllPosts 方法
func getAllPosts() {
let postRef = ref.child("posts")
postRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
// print(snapshot.value)
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let post = Post(key: key, dictionary: postDictionary)
FeedController.sharedFeedInstance.posts.insert(post, atIndex: 0)
}
}
}
})
}
【问题讨论】:
-
您的问题是您需要在屏幕上的视图控制器的上下文中执行
reloadData;FeedController().tableView.reloadData()创建FeedController的新实例,但没有帮助。获得所需内容的一种方法是从didSet发布 NSNotification 并让感兴趣的视图控制器订阅它。是的,全局变量是个坏主意。创建一个单例类或创建一个实例并将其传递给您的每个视图控制器 -
您需要知道
getAllPosts何时结束,然后才能调用reloadData。getAllPosts长什么样子?
标签: ios swift uitableview