我为什么得到:输入'任何'没有下标成员

时间:2017-11-25 21:45:17

标签: ios swift

我有这段代码,但它始终显示我:

  

键入'任何'没有下标成员

我不知道发生了什么。 提前谢谢你们,请解释一下我做错了什么,因为我不知道:(

 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
     }
 }

1 个答案:

答案 0 :(得分: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
}