iOS在TableView中创建空节
我正试图掌握TableView的使用,并试图以编程方式填充TableView。它进行得很顺利,但我想修改这个程序以创建空的部分,而不是预先填充的部分iOS在TableView中创建空节,ios,swift,uitableview,Ios,Swift,Uitableview,我正试图掌握TableView的使用,并试图以编程方式填充TableView。它进行得很顺利,但我想修改这个程序以创建空的部分,而不是预先填充的部分 import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var rowCount = 1 var sectionCount = 1 func numberOfSections(in
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var rowCount = 1
var sectionCount = 1
func numberOfSections(in tableView: UITableView) -> Int {
return sectionCount
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Section \(section+1)"
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rowCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath)
cell.textLabel?.text = "Entry \(indexPath.row+1) in Section \(indexPath.section+1)"
return cell
}
// func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//
// }
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var onSect: UISwitch!
@IBOutlet weak var addToTable: UIButton!
@IBAction func insertToTable(_ sender: Any) {
insert()
}
func insert(){
if onSect.isOn{
sectionCount += 1
}else{
rowCount += 1
}
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我可以看到,
reloadData()
基本上是基于tableView函数重新生成表的,但是我想不出任何方法,在调用reloadData()
的过程中,在不填充行的情况下创建一个节。您必须了解使用的tougout cococoa touch(以及cocoa)
TableView将其数据的知识委托给数据源
因此,数据源必须实现特定的方法,在您的情况下,我们最感兴趣的是:
func numberOfSections(in tableView: UITableView) -> Int
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
这两个函数将命令tableview的内容。
要开票的第一个功能是:
func numberOfSections(in tableView: UITableView) -> Int
根据您返回的内容,它将调用第二个方法,如果您希望tableview全部为空,则可以为数字返回0,如果部分为空,则其他函数甚至不会调用
如果您为numberOfSections
返回5,那么您将获得另一个函数的发票金额,并且您可以根据所获得的节索引参数返回所需的行数
以下是5个部分的示例,其中第三个部分为空,其余部分只有一行:
func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 2 {
return 0
}
return 1
}
是否要创建一个包含0行的节?基本上是的。为什么不在numberOfRowsInSection中返回0?是的,只需在该节的节中返回0而不是1行。您应该使用数据源,而不是为行数和节数设置静态值。例如,可以使用数字数组表示每个节中的行数,使用数组计数表示节数。如果您的目标是创建两个节,一个为空,另一个不为空,您需要在
numberofrowsinssection
和cellForRowAtIndexPath
中切换节索引,在cellForRowAtIndexPath
中,您可以从indexath
(函数参数)中获取节索引。这个答案教会了我很多关于如何工作的知识,让我看一个基于词典的答案,其中我将每个部分作为一个键,并使用一个数组跟踪添加到其中的项目数。它达到了我想要的效果,谢谢你。