Can I have a different number of rows in each section of a master-detail app?

喜欢而已 提交于 2020-01-14 19:12:26

问题


I'm new to Swift and iOS programming and I'm having a play with making some simple apps. I am trying to build a master-detail app.

In the master view I've given the tableview two sections and I've set the content of the table view to "static cells". Initially I gave each section 3 rows and was able to successfully run the app with the following code in the mainviewcontroller file:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

I am now wanting to have 11 rows in the first section, and 5 rows in the second section but the changes I have tried to the code prevent the app from running. I've tried:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 16
}

and I've tried:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 11
}

but it falls over. What am I doing wrong here?


回答1:


You should use the section to decide how many rows there should be in that section. For example, you could have a variable in your view controller:

let numberOfRowsAtSection: [Int] = [11, 5]

Now in numberOfRowsForSection:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var rows: Int = 0

    if section < numberOfRowsAtSection.count {
        rows = numberOfRowsAtSection[section]
    }

    return rows
}


来源:https://stackoverflow.com/questions/29472327/can-i-have-a-different-number-of-rows-in-each-section-of-a-master-detail-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!