2017-11-25 67 views
-6

我有這樣的代碼,但它總是顯示我:爲什麼我得到:類型「任何」無標會員

類型「任何」無標會員

我不不知道發生了什麼事。 謝謝你們提前,請給我解釋一下我做錯了什麼,因爲我不知道:(

import UIKit 
class PicturesViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {  
    var posts = NSDictionary() 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     posts = ["username" : "Hello"] 
    } 
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     return posts.count 
    } 
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PostCollectionViewCell 
     cell.usernameLbl.text = posts[indexPath.row]!["username"] as? String 
     cell.PictureImg.image = UIImage(named: "ava.jpg") 
     return cell 
    } 
} 

回答

0

你有一個NSDictionary的,但要使用它作爲一個數組,你需要的是一個數組的詞典。

我建議你改變你的代碼一點點。

var posts: [[String: String]] = [] // This creates an empty array of dictionaries. 

override func viewDidLoad() { 
    super.viewDidLoad() 
    posts = [ 
     [ "username": "Hello" ] // This adds a dictionary as an element of an array. 
    ] 
} 

... 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PostCollectionViewCell 
    cell.usernameLbl.text = posts[indexPath.row]["username"] // This will work now. 
    cell.PictureImg.image = UIImage(named: "ava.jpg") 
    return cell 
} 
相關問題