【发布时间】:2017-02-10 17:14:59
【问题描述】:
我想从包含图像字典(或任何类型的对象)的字典中读取数据。每个字典都有一个键(字符串)。
为了有点直观的理解,这是我想要实现的目标:
userIdOne -> [image1, image2, image3, image4]
userIdTwo -> [image1, image2, image3]
userIdThree -> [image1, image2, image3, image4, image5]
userIdFour -> [image1, image2]
注意:尽管“标题”相同,但这些图片并不是同一张图片。它们只属于每个单独的用户。 userId 是 [String:... 并且图像字典是我在这个问题的标题中提到的 [AnotherKindOfDictionary]。我想要每个单元格中的每个 userId 及其图像。所以总的来说,这将显示 4 个单元格,但是当点击时,它们的图像会按顺序显示。
问题是我想把这些数据放在 UITableView 或 UICollectionView 中。我之前和两者都合作过,所以无论哪个有效。 类似于 snapchat 的工作方式。每当点击一个单元格时,该用户的图像就会按顺序显示。
我已经能够将数据加载到字典中,每个用户 ID 都是键,但是我在使用 collectionView 中的数据时遇到了问题(我目前的选择,虽然我可以使用 tableView)
这是我的代码:
var stories = [String : [StoryMedia]]()
// StoryMedia is a struct containing info
struct StoryMedia {
var storyMediaId: String?
var creatorId: String?
var datePosted: String?
var imageUrl: String?
init(storyMediaKey: String, dict: Dictionary<String, AnyObject>) {
storyMediaId = storyMediaKey
creatorId = dict["creatorId"] as? String
datePosted = dict["dateposted"] as? String
imageUrl = dict["imageUrl"] as? String
}
}
... Now in the actual viewController class UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return stories.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let storyCell: StoryCell!
storyCell = collectionView.dequeueReusableCell(withReuseIdentifier: storyReuseIdentifier, for: indexPath) as! StoryCell
// What should I do here?
return storyCell
}
问题在于尝试设置每个单元格。我无法通过键提取每个字典值并将其用于每个单元格。
我尝试过使用:
// Failed attempt 1)
let story = stories[indexPath.row]
// but I get an ambiguous reference to member 'subscript' error
// Failed attempt 2)
for story in stories {
let creatorId = story.key
let sequenceOfStoryItems = story.value
for singleStoryItem in sequenceOfStoryItems {
// do something...
}
}
// but looping through an array for a collection view cell
// does nothing to display the data and if I were to guess,
// would be detrimental to memory if
// I had a lot of "friends" or users in my "timeline"
【问题讨论】:
标签: ios swift uitableview dictionary uicollectionview