Arrays 需要为我的CollectionView获取字典中的数组计数

Arrays 需要为我的CollectionView获取字典中的数组计数,arrays,swift,dictionary,count,uicollectionview,Arrays,Swift,Dictionary,Count,Uicollectionview,好的,我试着让我的CollectionView每个部分都有一个标题,每个部分中有3个带有相应标签的ImageView。我有与标签匹配的图像视图,但在返回正确的numberOfItemsInSection时遇到问题。 为了解决这个问题,我已经多次更改代码,我甚至不确定我的应用程序的其余部分是否正确,但本质上这是最重要的部分: var sectionsArrayDictionary : [String:Array<String>] = ["level 1" : ["item1", "it

好的,我试着让我的CollectionView每个部分都有一个标题,每个部分中有3个带有相应标签的ImageView。我有与标签匹配的图像视图,但在返回正确的numberOfItemsInSection时遇到问题。 为了解决这个问题,我已经多次更改代码,我甚至不确定我的应用程序的其余部分是否正确,但本质上这是最重要的部分:

var sectionsArrayDictionary : [String:Array<String>] = ["level 1" : ["item1", "item2", "item3"], "level 2" : ["item4","item5", "item6"], "level 3" : ["item7", "item8", "item9"]]
我试图去掉sectionData(它上面有一个代码块,上面有let节、let s1data和var节)。这毫无帮助。 我试着把它换成

class SectionsData {

func getSectionsFromData() -> [Section] {

    // you could replace the contents of this function with an HTTP GET, a database fetch request,
    // or anything you like, as long as you return an array of Sections this program will
    // function the same way.

    var sectionsArray = [Section]()

    let level1 = Section(title: "Level 1", objects: ["max", "roxy", "buster"])
    let level2 = Section(title: "Level 2", objects: ["daisy","charlie", "maggie"])
    let level3 = Section(title: "Level 3", objects: ["buddy", "ruby", "lucky"])


    sectionsArray.append(level1)
    sectionsArray.append(level2)
    sectionsArray.append(level3)

    return sectionsArray
}
}

及 结构截面{

    var heading : String
    var items : [String]

    init(title: String, objects : [String]) {

        heading = title
        items = objects

    }
}

不幸的是,我无法将标题、项目、标题或对象作为主视图页面上的成员调用……因此,给定一个节字符串,我现在就卡住了

let count = sectionsArrayDictionary["level 1"].count
我知道肯定还有更多,所以你需要发布更多的代码让我们更好地理解这个问题

更新: 因此,我们仍然缺少
部分
的关键声明,但假设您可以直接访问其
对象
属性;这就是您所需要的

let count = sections[1].objects.count

对于二级对象daisy、charlie和maggie,count变量现在应该是3。接下来,您应该只为Swift 3开发,很快为4开发。在本项目中不要中途切换,但是没有人使用Swift 2开发。任何在线Swift 2教程都过时了。祝您好运。

首先,如何从Dic获取count临时:

var sectionsArrayDictionary : [String:Array<String>] = ["level 1" : ["item1", "item2", "item3"], "level 2" : ["item4","item5", "item6"], "level 3" : ["item7", "item8", "item9"]]

let sectionIndex = 0
let sectionName = "level \(sectionIndex+1)" //->level 1
if let sectionItems = sectionsArrayDictionary[sectionName] {
    let count = sectionItems.count
    print(count)
} else {
    print("No entry for '\(sectionName)'")
}
在代码中,您分别处理每个项目的标签文本和图像名称,因此引入了
item
类型以分别保存它们


数据
在应用程序中使用得太频繁,因此我将其重命名为
SectionsManager
。此外,不建议每次使用时都创建一个实例,目前首选的方式是单例模式

class SectionsManager {

    //### Singleton
    static let shared = SectionsManager()
    private init() {}

    func getSectionsFromData() -> [Section] {

        // you could replace the contents of this function with an HTTP GET, a database fetch request,
        // or anything you like, as long as you return an array of Sections this program will
        // function the same way.

        var sectionsArray = [Section]()

        let level1 = Section(title: "Level 1", objects: ["max", "roxy", "buster"])
        let level2 = Section(title: "Level 2", objects: ["daisy","charlie", "maggie"])
        let level3 = Section(title: "Level 3", objects: ["buddy", "ruby", "lucky"])


        sectionsArray.append(level1)
        sectionsArray.append(level2)
        sectionsArray.append(level3)

        return sectionsArray
    }

    func getSectionsFromDictionary(dictionary: [String: [String]]) -> [Section] {
        var sectionsArray = [Section]()

        //###  `.sort({$0.0 < $1.0})` sorts the dictionary by its key.
        for (title, objects) in dictionary.sort({$0.0 < $1.0}) {
            //print(title, objects) //See what is happening while debugging.
            let level = Section(title: title, objects: objects)

            sectionsArray.append(level)
        }

        return sectionsArray
    }
}

您可能需要一些修复程序才能使此代码在您的项目中正常工作,但我希望它不会太多,您可以自己完成。

这里使用此工具获取您的分区ArrayDictionary中的数组总数

var sectionsArrayDictionary : [String:Array<String>] = ["level 1" : ["item1", "item2", "item3"], "level 2" : ["item4","item5", "item6"], "level 3" : ["item7", "item8", "item9"]]

var keys = Array(sectionsArrayDictionary.keys)
print(keys)

print(keys.count) //Output - 3
var sectionsArrayDictionary:[字符串:数组]=[“级别1”:[“项目1”、“项目2”、“项目3”],“级别2”:[“项目4”、“项目5”、“项目6”],“级别3”:[“项目7”、“项目8”、“项目9”]
var keys=数组(sectionsArrayDictionary.keys)
打印(钥匙)
打印(keys.count)//输出-3

请出示您的代码。我们无法在不看到的情况下修复任何代码。您使用的是Xcode 7/Swift 2吗?Xcode 7是的,老实说,我不知道Swift 2.x随附的是哪个版本的Swift Xcode 7,Swift从2到3在许多方面都发生了变化。我建议您将Xcode更新为最新版本,并找到适合更新后的Xcod的教程或示例代码e、 您可能需要升级macOS,但您可以免费获得Xcode和macOS升级。(您只需要足够的磁盘空间进行升级。)尽管这可能需要一些时间,所以我将尝试在Swift 2中写一个答案。“使用未解析标识符”如果我这样做。谢谢你。我发布了更多的代码来帮助你。非常感谢,我的代码不再显示错误,我的collectionView现在在第一页上显示正确的图片:)很高兴听到这个消息。希望你的进一步发展不会出现问题。但是如果你发现一些困难,我很乐意帮助你。祝你好运。
class SectionsManager {

    //### Singleton
    static let shared = SectionsManager()
    private init() {}

    func getSectionsFromData() -> [Section] {

        // you could replace the contents of this function with an HTTP GET, a database fetch request,
        // or anything you like, as long as you return an array of Sections this program will
        // function the same way.

        var sectionsArray = [Section]()

        let level1 = Section(title: "Level 1", objects: ["max", "roxy", "buster"])
        let level2 = Section(title: "Level 2", objects: ["daisy","charlie", "maggie"])
        let level3 = Section(title: "Level 3", objects: ["buddy", "ruby", "lucky"])


        sectionsArray.append(level1)
        sectionsArray.append(level2)
        sectionsArray.append(level3)

        return sectionsArray
    }

    func getSectionsFromDictionary(dictionary: [String: [String]]) -> [Section] {
        var sectionsArray = [Section]()

        //###  `.sort({$0.0 < $1.0})` sorts the dictionary by its key.
        for (title, objects) in dictionary.sort({$0.0 < $1.0}) {
            //print(title, objects) //See what is happening while debugging.
            let level = Section(title: title, objects: objects)

            sectionsArray.append(level)
        }

        return sectionsArray
    }
}
class LayoutController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
    var sectionsArrayDictionary : [String: [String]] = ["level 1" : ["item1", "item2", "item3"], "level 2" : ["item4","item5", "item6"], "level 3" : ["item7", "item8", "item9"]]

    let sectionInsets = UIEdgeInsets(top: 5.0, left: 5.0, bottom: 5.0, right: 5.0)

    //### With using an Array of Section, your code gets simplified.
    var sections: [Section] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        //### Choose any one you prefer.
        //sections = SectionsManager.shared.getSectionsFromData()
        sections = SectionsManager.shared.getSectionsFromDictionary(sectionsArrayDictionary)
    }

    // MARK: UICollectionViewDataSource

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return sections.count
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //### Return the number of items in the specified section.
        return sections[section].items.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
        //### Your old code does not use `indexPath.section`, so all sections show the same contents.
        let sectionIndex = indexPath.section
        let itemIndex = indexPath.row
        let item = sections[sectionIndex].items[itemIndex]
        cell.animalImage.image = UIImage(named: item.imageName)
        cell.animalLabel.text = item.labelText
        return cell
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        return sectionInsets
    }

    func collectionView(collectionView: UICollectionView, titleForHeaderInSection section:Int) -> String? {
        //### Try this.
        return sections[section].heading
    }

    override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        //### Not sure what you really want to do here, so keeping it as is.

        let headerView: Header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: headerViewIdentifier, forIndexPath: indexPath) as! Header

        headerView.headerLabel.text = "Level"

        return headerView

    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        print(segue.identifier)
        print(sender)
        if(segue.identifier == "detail"){
            let cell = sender as! CollectionViewCell
            //### Do nothing when `indexPath` cannot be gotten.
            guard let indexPath = collectionView!.indexPathForCell(cell) else {return}
            let vc = segue.destinationViewController as! DetailViewController

            //### You can retrieve the item in the same way as `collectionView(_:cellForItemAtIndexPath:)`.
            let sectionIndex = indexPath.section
            let itemIndex = indexPath.row
            let item = sections[sectionIndex].items[itemIndex]
            let imgName = item.imageName

            print(vc)
            vc.currImage = UIImage(named: imgName)
            vc.textHeading = item.labelText
            //...
        }
    }
}
var sectionsArrayDictionary : [String:Array<String>] = ["level 1" : ["item1", "item2", "item3"], "level 2" : ["item4","item5", "item6"], "level 3" : ["item7", "item8", "item9"]]

var keys = Array(sectionsArrayDictionary.keys)
print(keys)

print(keys.count) //Output - 3