无法在 tableView 中插入新行 [英] Can't insert new row in tableView

查看:29
本文介绍了无法在 tableView 中插入新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道问题已经解决了很多次,但没有一种方法对我有帮助.

I understand that the problem has been solved many times, but none of the ways helped me.

我想在 tableView 中插入新行.我有三个部分,在第二个和第三个部分中,我有 UIButton,它可以将新行推断为所需的部分,但我在控制台中收到错误.可能是什么问题?

I want to insert new row in tableView. I have three sections and in second and third sectons I have UIButton which can infert new row to the desired section, but I receive error in console. what could be the problem?

我插入新行时的错误 - 尝试将第 2 行插入第 1 节,但更新后第 1 节中只有 2 行

My error when I insert new row - attempt to insert row 2 into section 1, but there are only 2 rows in section 1 after the update

还有我的代码:

class SettingsScheduleAndPricesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var saveBarButtonItem: UIBarButtonItem!
    @IBOutlet weak var backBarButtonItem: UIBarButtonItem!

    let sectionTitle = ["Day of week", "Second section", "Third section"]
    var secondRowText = ["First row", "Second row"]
    var thirdRowText = ["Row one", "Row two", "Row three"]

    override func viewDidLoad() {
        super.viewDidLoad()    
    }
    // MARK: - TableView
    func numberOfSections(in tableView: UITableView) -> Int {
        return sectionTitle.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0: return 1
        case 1: return 2
        default: return 3
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let collectionCell = tableView.dequeueReusableCell(withIdentifier: "collectionCell", for: indexPath) as! SettingsCollectionViewCell
            return collectionCell
        } else if indexPath.section == 1 {
            let hourlyRateCell = tableView.dequeueReusableCell(withIdentifier: "hourlyRateCell", for: indexPath) as! SettingsHourlyRateCell
            hourlyRateCell.textLabel?.text = secondRowText[indexPath.row]
            return hourlyRateCell
        } else {
            let datePriceCell = tableView.dequeueReusableCell(withIdentifier: "datePriceCell", for: indexPath) as! SettingsDatePriceCell
            datePriceCell.textLabel?.text = thirdRowText[indexPath.row]
            return datePriceCell
        }
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.sectionTitle[section]
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let frame: CGRect = tableView.frame
        if section == 0 {
            let headerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
            headerView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
            return headerView
        } else if section == 1 {
            let addButton: UIButton = UIButton(frame: CGRect(x: frame.size.width - 50, y: 0, width: 50, height: 30))
            addButton.backgroundColor = UIColor.clear
            addButton.setTitleColor(#colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1), for: .normal)
            addButton.setTitle("Add", for: .normal)
            addButton.addTarget(self, action: #selector(SettingsScheduleAndPricesViewController.addHourlyRate(sender:)), for: .touchUpInside)
            let headerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
            headerView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
            headerView.addSubview(addButton)
            return headerView
        } else {
            let addButton: UIButton = UIButton(frame: CGRect(x: frame.size.width - 50, y: 0, width: 50, height: 30))
            addButton.backgroundColor = UIColor.clear
            addButton.setTitleColor(#colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1), for: .normal)
            addButton.setTitle("Add", for: .normal)
            addButton.addTarget(self, action: #selector(SettingsScheduleAndPricesViewController.addDatePrice(sender:)), for: .touchUpInside)
            let headerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
            headerView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
            headerView.addSubview(addButton)
            return headerView
        }
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }

    @objc func addHourlyRate(sender: UIButton) {
        let newRow: String = "Third row"
        secondRowText.append(newRow)
        let indexPath = IndexPath(row: secondRowText.count - 1, section: 1)
        tableView.beginUpdates()
        tableView.insertRows(at: [indexPath], with: .automatic)
        tableView.endUpdates()
    }

    @objc func addDatePrice(sender: UIButton) {
        let newRow: String = "Row four"
        thirdRowText.append(newRow)
        let indexPath = IndexPath(row: thirdRowText.count - 1, section: 2)
        tableView.beginUpdates()
        tableView.insertRows(at: [indexPath], with: .automatic)
        tableView.endUpdates()
    }
}

delegatedataSource 我在 storyboard

请不要因为重复问题而责骂,我找到的所有答案都没有帮助我

Please do not scold for repeating the question, nothing helps me of all the answers that I found

推荐答案

强烈建议不要对 numberOfSectionsnumberOfRowsInSection 的返回值进行硬编码.这导致了错误.

It's strongly discouraged to hard-code the return value of numberOfSections and numberOfRowsInSection. This caused the error.

另一方面,强烈建议您使用自定义结构作为数据模型.这样效率更高,并且避免了这些错误.

On the other hand you are highly encouraged to use a custom struct as data model. This is much more efficient and avoids those mistakes.

struct Section {
    let title : String
    var rows : [String]
}

<小时>

class SettingsScheduleAndPricesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var saveBarButtonItem: UIBarButtonItem!
    @IBOutlet weak var backBarButtonItem: UIBarButtonItem!

    var sections = [Section]()

    override func viewDidLoad() {
        super.viewDidLoad()
        sections = [Section(title: "Day of week", rows: []),
                    Section(title: "Second section", rows: ["First row", "Second row"]),
                    Section(title: "Day of week", rows: ["Row one", "Row two", "Row three"])]
    }

    // MARK: - TableView
    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].rows.count
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section].title
    }

/*  
    `cellForRowAt`, `viewForHeaderInSection` and `heightForHeaderInSection` omitted
*/

    @objc func addHourlyRate(sender: UIButton) {
        let newRow = "Third row"
        append(row: newRow, in: 1)
    }

    @objc func addDatePrice(sender: UIButton) {
        let newRow = "Row four"
        append(row: newRow, in: 2)
    }

    func append(row : String, in section: Int) {
        let insertionIndex = sections[section].rows.count
        sections[section].rows.append(row)
        let indexPath = IndexPath(row: insertionIndex, section: section)
        tableView.insertRows(at: [indexPath], with: .automatic)
    }
}

这篇关于无法在 tableView 中插入新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆