为什么我得到:类型“任何”无标会员
问题描述:
我有这样的代码,但它总是显示我:为什么我得到:类型“任何”无标会员
类型“任何”无标会员
我不不知道发生了什么事。 谢谢你们提前,请给我解释一下我做错了什么,因为我不知道:(
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
}
}
答
你有一个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
}