Ios 为什么collectionView上没有显示任何内容?
我有一个collectionview和一个带有字符串用户名的数组,该数组连接到parse,但是当我运行程序时,collectionview不会显示任何内容。我通过在数组中手动输入值来硬编码它,它工作了,但一旦我从parse中检索字符串,它就不工作了。我该如何解决这个问题Ios 为什么collectionView上没有显示任何内容?,ios,swift,uicollectionview,Ios,Swift,Uicollectionview,我有一个collectionview和一个带有字符串用户名的数组,该数组连接到parse,但是当我运行程序时,collectionview不会显示任何内容。我通过在数组中手动输入值来硬编码它,它工作了,但一旦我从parse中检索字符串,它就不工作了。我该如何解决这个问题 var arrayOfFriendsNames = [String]() var arrayOfFriendsTest: [String] = ["fire.png, fire.png, fire.png"] override
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
}
从
Parse
加载完数据后,确保在UICollectionView
实例上调用reloadData
方法。如果是,请检查UICollectionView
的约束,并确保它们是正确的。另一种可能是Parse
不向代码返回任何数据,因此请确保数组中包含有效数据
代码的问题在于调用的位置self.collectionView.reloadData()
。您需要在findobjectsinbackgroundithblock
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回答了在从数据库获取完数据后尝试重新加载
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()
}
})
设置collectionview的数据源和委托。我已经这样做了。当您在
collectionview:numberOfItemsInSection:
上放置断点时,是否会调用它?如果是,则填充arrayOfFriendsNames.count
arrayOfFriendsNames的值是多少,它对应于解析数据库,但当我放置断点时,arrayOfFriendsNames不会出现在控制台中。