2016-07-31 21 views
0

我一直在學習如何使用UICollection視圖。我製作了一個新的UICollectionView控制器,並在main.storyboard中將collectionView單元識別爲「單元」。無論何時點擊UICollectionView控制器(通過TapBar控制器),我都會顯示黑屏,我正在使用Firebase導入/導出數據。 謝謝你的幫助!黑UICollectionView

class UserCollectionViewController: UICollectionViewController { 
     var databaseRef = FIRDatabase.database().reference() 
     var usersDict = NSDictionary?() 

     var userNameArray = [String]() 
     var userImageArray = [String]() 

     override func viewDidLoad() { 
      super.viewDidLoad() 


      self.databaseRef.child("user_profile").observeEventType(.Value, withBlock :{ 
       (snapshot) in 
       self.usersDict = snapshot.value as? NSDictionary 
       for(userId,details) in self.usersDict! { 
        let img = details.objectForKey("profile_pic_small") as! String 
        let name = details.objectForKey("name") as! String 
        let firstName = name.componentsSeparatedByString(" ")[0] 
        self.userImageArray.append(img) 
        self.userNameArray.append(firstName) 
        self.collectionView?.reloadData() 
       } 


      }) 

     } 
      override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { 
       return 1 
      } 

      override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
       return self.userImageArray.count 
      } 

      override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 

      let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollectionViewCell 
      return cell 


       let imageUrl = NSURL(string: userImageArray[indexPath.row]) 
       let imageData = NSData(contentsOfURL: imageUrl!) 

       cell.userImage.image = UIImage(data: imageData!) 
       cell.userName.text = userNameArray[indexPath.row] 

       return cell 
     } 

    } 
+0

您從不爲單元格設置大小:'sizeForItemAtIndexpath'。此外,你的代碼有一個錯字:'self'而不是'elf'。檢查你的'userImageArray'是否有項目。 – Brandon

+0

圖像數組具有URL值,我不認爲有任何「精靈」,因爲我可以運行該程序而不會崩潰。我通過故事板製作了單元大小,但它是否與CollectionViewController的顏色無關? –

+0

你的問題只是你沒有進行基本調試的問題。下載並使用[Apple的UIViewController演示應用程序](https://developer.apple.com/library/prerelease/content/samplecode/CollectionView-Simple/Introduction/Intro.html)。 – Jeff

回答

0

在單元格中放置一個UIView(相對於單元格將其約束設置爲0,0,0,0),然後添加imageView併爲其添加標籤。另外不要忘記遵守代表和數據源。