字典中讀取數據我想從包含圖像字典(或任何類型的對象)的字典中讀取數據。每個字典都有一個鍵(字符串)。iOS Swift從[字符串:[AnotherKindOfDictionary]]()
對於有些直觀的瞭解這就是我想實現:
userIdOne - > [圖像1,圖像2,圖像3,圖像4]
userIdTwo - > [圖像1,圖像2,圖像3]
userIdThree - > [圖像1,圖像2,圖像3,圖像4,圖像5]
userIdFour - > [圖像1,圖像2]
注意:這些圖像是n儘管擁有相同的「標題」,但仍有相同的圖像。他們只屬於每個個人用戶。 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"
我試着用let storyKeys = stories.keys。然後讓singleStoryKey = storyKeys [indexPath.row]。我仍然得到一個錯誤 –
我不清楚你爲什麼看着鑰匙。cellForItem給你一個索引,所以在字典的值上使用該索引並忽略字典的鍵。你遇到了什麼錯誤? – ghostatron
@ conarch關鍵是每個細胞。每個單元格代表一個用戶。字典中的每個鍵都是用戶的ID。從中我可以檢索他們的用戶名,profileImage等。值是所有故事項目(視頻,圖像,任何)的陣列。一旦單元被接通,該值將按順序「播放」。因此,我需要字典中每個數組的鍵以加載正確的故事數組 –