繁体   English   中英

不知道节(Swift)中的行数

[英]don't know the number of rows in section (swift)

在我看来,tableview的每一行都是可以填充的任务,并且每次打开应用程序时,tableView的每一行都应该是先验的。 (如您在图片中看到的)

我也有按钮,它允许您添加一行。 但是我不知道如何知道节中的行数。 您能帮我吗?(在我的代码中,我评论了我无法理解的时刻)

class TaskSecondViewController: UIViewController,UITableViewDataSource{

 @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        self.tableView.separatorColor = UIColor.clear

 @IBAction func insert_rows(_ sender: Any) {

   let indexPath = IndexPath(row: 1, section: 1) // Don't know what to write in "row"
    self.tableView.insertRows(at: [indexPath], with: .top)

    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return 1 // Here also
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TaskTableViewCell

        return cell
    }

}

你可以简单地拥有

var numOfRow = 0

每次您按下按钮

numberOfRow += 1
tableView.reloadData()

所以你可以返回numberOfRow

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return numOfRow
}

你试过这个吗:

yourTableView.numberOfRows(inSection: 0)

这将返回表视图部分的行数

但是我不知道如何知道节中的行数。

要了解的重要一点是,表格不了解其显示的项目,如何显示它们,或者与人们进行交互时不知道如何做。 表格实际上只是部分列表,其中每个部分都是单元格列表。 它可以滚动。 它可以寻求帮助。

显示的项目保留在其他位置。 它们甚至都不是同时作为表中的行存在的。 该表仅保留需要显示的行数,并且当用户滚动时,它要求其他对象显示更多的行,并丢弃不再显示的行。 另一个对象是数据源,它可能是保存项目的“其他地方”,也可能只是知道在哪里查找(或生成)这些项目的对象。

在这种情况下,您的TaskSecondViewController视图控制器是表的数据源。 您需要确保该控制器以某种方式可以访问其所需的数据。 也许它从文件中读取列表。 也许从其他对象传入项目数组。 主题有上百万个变体,但是要由您决定要在表中显示什么,并知道这些内容的存放位置。 知道这一点后,您应该能够找出给定部分中有多少个项目。 您还需要知道有多少部分。 可能是您只有一个项目列表,并且您不打算将其分解为几个部分。 在这种情况下,您只需返回1作为部分的数目,并返回整个列表中的项目数作为该部分的行数。

如果只想添加一行,则不必在明确的位置将其插入到表视图中。 具有一个数组(或字典或其他东西)并将您的项目添加到该对象中,然后在添加项目时重新加载表格视图会更容易。

var itemsToDisplay = [SomeObject]

override func viewDidLoad() { 

    // populate items if needed

}

@IBAction func insert_rows(_ sender: Any) {

   // get your data to create your object
   // add your object to itemsToDisplay
   itemsToDisplay.append(myObject)

   // for a TableViewController
   self.tableView.reloadData()

   // if you've included the tableView as an @IBOutlet
   myTableView.reloadData()

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return itemsToDisplay.count // this might be zero, but it doesn't matter
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TaskTableViewCell

    var item = itemsToDisplay[indexPath.row]

    cell.titleLabel.text = item.whatever

    return cell
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM