2015-04-06 25 views
2

我是新来的Swift和iOS编程,我正在玩一些简单的应用程序。我正在尝试构建一个主 - 细节应用程序。我可以在主 - 从应用程序的每个部分中有不同数量的行吗?

在主视图中,我给了tableview两个部分,并将表视图的内容设置为“静态单元格”。起初,我给每个第3行,并能与在mainviewcontroller文件下面的代码成功运行应用程序:

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

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

我现在想在首节11行,并在第二个5行部分,但我尝试过的代码阻止应用程序运行。我已经试过:

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

,我已经试过:

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

但它倒下。我在这里做错了什么?

+1

使用则传递给你的款号,以决定是否返回11个或5 – 2015-04-06 13:42:11

+0

感谢。我没有意识到我可以在方法中引用“部分”。 – Woody 2015-04-07 10:12:14

回答

12

您应该使用section来决定该部分应该有多少行。例如,你可以有一个变量在您的视图控制器:

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

现在numberOfRowsForSection

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

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

    return rows 
} 
+0

我该如何参考每个部分中的行?例如,如果我想让第一部分的行表示“Hi”,第二部分的行表示“hello”,那么我如何区分'cellForRowAt IndexPath'中的行呢?他们增加到总数(如果有两个部分,一个是11,一个是5行......最后一行的最后一行是第15行?)? – 2016-10-31 18:14:25

+1

请问这个问题的答案(http://stackoverflow.com/questions/29578965/how-do-i-populate-two-sections-in-a-tableview-with-two-different-arrays-using- sw/29579027#29579027)有帮助吗? :) – ABakerSmith 2016-11-01 00:46:26

相关问题