2015-10-26 123 views
0

我有一个collectionview,我有一个连接到解析的字符串username的数组,但是当我运行该程序时collectionview不显示任何东西。我通过在数组中手动​​输入值来对它进行硬编码,并且它工作正常,但是一旦从解析中检索字符串,它就不起作用。我该如何解决?为什么没有显示在collectionView上?

var arrayOfFriendsNames = [String]() 
var arrayOfFriendsTest: [String] = ["fire.png, fire.png, fire.png"] 
override func viewDidLoad() { 
    super.viewDidLoad() 

    var query = PFQuery(className: "_User") 
    query.findObjectsInBackgroundWithBlock({ 
     (objects: [AnyObject]?, error: NSError?) -> Void in 
     var objectIDs = objects as! [PFObject] 

     for i in 0...objectIDs.count-1{ 
      self.arrayOfFriendsNames.append(objectIDs[i].valueForKey("username") as! String) 
      print(self.arrayOfFriendsNames) 
     } 
    }) 
self.collectionView.reloadData() 
} 
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return arrayOfFriendsNames.count 
} 
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell: friendcellView = collectionView.dequeueReusableCellWithReuseIdentifier("friendcell", forIndexPath: indexPath) as! friendcellView 


    cell.friendname.text = arrayOfFriendsNames[indexPath.row] 
    cell.friendpic.image = UIImage(named: arrayOfFriendsTest[indexPath.row]) 
    cell.friendpic.layer.cornerRadius = cell.friendpic.frame.size.width/2; 
    cell.friendpic.clipsToBounds = true 

    return cell 
} 
+0

设置数据源和代表collectionview的。 – pkc456

+0

我已经完成了。 – xxtmanxx

回答

0

尝试从DB

重装完成后,获得的数据
query.findObjectsInBackgroundWithBlock({ 
     (objects: [AnyObject]?, error: NSError?) -> Void in 
     var objectIDs = objects as! [PFObject] 

     for i in 0...objectIDs.count-1{ 
      self.arrayOfFriendsNames.append(objectIDs[i].valueForKey("username") as! String) 
      print(self.arrayOfFriendsNames) 
     } 

     dispatch_async(dispatch_get_main_queue()) { 
      self.collectionView.reloadData() 
     } 

    }) 
0

确保你在你的UICollectionView实例调用reloadData方法,当你从Parse完成加载数据。如果是,请检查您的约束UICollectionView并确保它们是正确的。另一种可能性是Parse不会向您的代码返回任何数据,因此请确保您的数组中包含有效数据。

您的代码问题是您拨打self.collectionView.reloadData()的地方。你需要调用它的findObjectsInBackgroundWithBlock

query.findObjectsInBackgroundWithBlock({ 
    (objects: [AnyObject]?, error: NSError?) -> Void in 
    var objectIDs = objects as! [PFObject] 

    for i in 0...objectIDs.count-1{ 
     self.arrayOfFriendsNames.append(objectIDs[i].valueForKey("username") as! String) 
     print(self.arrayOfFriendsNames) 
    } 
    NSOperationQueue.mainQueue().addOperationWithBlock {() -> Void in 
     self.collectionView.reloadData() 
    } 
}) 

里面你还可以使用GCD方式作为@anhtu回答

+0

当你在'collectionView:numberOfItemsInSection:'上放置一个断点时,它会被调用吗?如果是,'arrayOfFriendsNames.count'的值是什么? – manman

+0

arrayOfFriendsNames被填充,它对应于解析数据库,但是当我放置断点时,arrayOfFriendsNames不会出现在控制台中。 – xxtmanxx