草庐IT

ios - 更新 (15) 后现有部分中包含的行数必须等于

coder 2023-09-10 原文

所以我将构建一个应用程序作为一种爱好并进行了研究,似乎有几个人有类似的问题,除了我的问题发生在开始插入数据时。所以我认为它略有不同。

当我将数据插入我的数组和表格时,它返回一个错误(标题),它检索了正确数量的当前计数,但很难添加一个新的。

class AccountsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var totalLabel: UILabel!
    @IBOutlet weak var tableview: UITableView!
    @IBOutlet weak var tableview2: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        //Set the table background as the image
        tableview.backgroundView = UIImageView(image: UIImage(named: "splasnowords-1.png"))

        //Use the edit button item provided by the table view controller
        navigationItem.leftBarButtonItem = editButtonItem
        //self.navigationItem.leftBarButtonItem = self.editButtonItem;

        //Calculate the latest totalstandings
        BudgetDataModel.calculateTotalStandings()
        totalLabel.text = ("Total Current Standings = £\(BudgetDataModel.returnTrueValue(number: BudgetDataModel.total))")

        self.tableview.delegate = self
        self.tableview2.delegate = self
        self.tableview.dataSource = self
        self.tableview2.dataSource = self
    }

    // MARK: - Table view data source
    func numberOfSections(in tableView: UITableView) -> Int {
        if (tableView == tableview){
        return 1
            //BudgetDataModel.budgets.count
        }
        else{
            return 2
                //SavingsDataModel.savings.count
        }
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?{
        //reload data?
        if (tableView == tableview){
            return "Budgets"
        }
        else{
            return "Savings"
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var rowCount = 0
        if (tableView == self.tableview) {
            rowCount = BudgetDataModel.budgets.count
        }
        if (tableView == self.tableview2) {
            rowCount = SavingsDataModel.savings.count
        }
        return rowCount

        // #warning Incomplete implementation, return the number of rows
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       //Table view cells are reused and should be dequeued using a cell identifier.
        if (tableView == self.tableview){
            let cellIdentifier = "AccountsTableViewCell"
            let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! AccountsTableViewCell

            let budget = BudgetDataModel.budgets[(indexPath as NSIndexPath).row]

            cell.nameLabel.text = budget.name
            cell.amountLabel.text = ("£\(BudgetDataModel.returnTrueValue(number: budget.amount))")
            cell.backgroundColor = UIColor(white: 1, alpha: 0.5)
            return cell
        }
        else if (tableView == self.tableview2){
            let cellIdentifier = "SavingsTableViewCell"
            let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! SavingsTableViewCell
            let saving = SavingsDataModel.savings[(indexPath as NSIndexPath).row]

            cell.savingsnameLabel.text = saving.savingname
            cell.savingsamountLabel.text = ("£\(BudgetDataModel.returnTrueValue(number: saving.savingamount))")
            cell.backgroundColor = UIColor(white: 1, alpha: 0.5)
            return cell
         }
        else { preconditionFailure ("unexpected cell type") }
    }

    // Override to support conditional editing of the table view.
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }

    // Override to support editing the table view.
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            if (tableView == tableview){
                // Delete the row from the data source
                BudgetDataModel.budgets.remove(at: indexPath.row)
                BudgetDataModel.saveBudgets()
                BudgetDataModel.calculateTotalStandings()
                totalLabel.text = ("Total Current Standings = £\(BudgetDataModel.returnTrueValue(number:BudgetDataModel.total))")
               // self.tableview.reloadData()
                tableView.deleteRows(at: [indexPath], with: .fade)

            }
            else if (tableView == tableview2){
                // Delete the row from the data source
                SavingsDataModel.savings.remove(at: indexPath.row)
                SavingsDataModel.saveSavings()
                //implement   BudgetDataModel.calculateTotalStandings()
                //implement   totalLabel.text = ("Total Current Standings = £\(BudgetDataModel.returnTrueValue(number:BudgetDataModel.total))")
                //self.tableview2.reloadData()
                tableView.deleteRows(at: [indexPath], with: .fade)

            }
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }

    // Override to support rearranging the table view.
    func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
    }

    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ShowDetail"{
            let budgetDetailViewController = segue.destination as! BudgetViewController
            //Get the cell that generated this segue.
            if let selectedBudgetCell = sender as? AccountsTableViewCell {
                let indexPath = tableview.indexPath(for: selectedBudgetCell)!
                let selectedBudget = BudgetDataModel.budgets[indexPath.row]
                budgetDetailViewController.budget = selectedBudget
            }
        }
        else if segue.identifier == "AddItem"{
            //self.tableview.reloadData()
            print("Adding new budget.")
        }
        else if segue.identifier == "ShowSavings"{
                let savingDetailViewController = segue.destination as! SavingsViewController
                //Get the cell that generated this segue.
                if let selectedSavingsCell = sender as? SavingsTableViewCell {
                    let indexPath = tableview2.indexPath(for: selectedSavingsCell)!
                    let selectedSavings = SavingsDataModel.savings[indexPath.row]
                    savingDetailViewController.saving = selectedSavings
                }
        }
        else if segue.identifier == "AddSaving"{
            //self.tableview2.reloadData()
            print ("Adding new saving.")
        }
    }

    //MARK: Actions

    @IBAction func unwindToBudgetList(_ sender: UIStoryboardSegue){
        if let sourceViewController = sender.source as? BudgetViewController, let budget = sourceViewController.budget {
            if let selectedIndexPath = tableview.indexPathForSelectedRow{
                //Update an existing budget.
                BudgetDataModel.budgets[selectedIndexPath.row] = budget
                tableview.reloadRows(at: [selectedIndexPath], with: .none)
            }
            else{
                    //Add a new budget
                    let newIndexPath = IndexPath(row:BudgetDataModel.budgets.count, section: 0)
                    BudgetDataModel.budgets.append(budget)
                    tableview.insertRows(at: [newIndexPath as IndexPath], with: .bottom)
                }
            //Save the budgets.
            BudgetDataModel.saveBudgets()
            BudgetDataModel.calculateTotalStandings()
            totalLabel.text = ("Total Current Standings = £\(BudgetDataModel.returnTrueValue(number: BudgetDataModel.total))")

        }
    }

    @IBAction func unwindtoSavingsList(_ sender: UIStoryboardSegue){
        if let sourceViewController = sender.source as? SavingsViewController, let savings = sourceViewController.saving {
            if let selectedIndexPath = tableview2.indexPathForSelectedRow{
                //Update an existing budget.
                SavingsDataModel.savings[selectedIndexPath.row] = savings
                tableview2.reloadRows(at: [selectedIndexPath], with: .none)
            }
            else{
                //Add a new saving
                let newIndexPath = IndexPath(row:SavingsDataModel.savings.count, section: 1)
                SavingsDataModel.savings.append(savings)
                //tableview2.reloadData()
                tableview2.insertRows(at: [newIndexPath as IndexPath], with: .bottom)
            }
            //Save the budgets.
            SavingsDataModel.saveSavings()
            //implement    SavingsDataModel.calculateTotalStandings()
            //    totalLabel.text = ("Total Current Standings = £\(BudgetDataModel.returnTrueValue(number: BudgetDataModel.total))")

        }
    }
}

最佳答案

感谢@jcaron

需要更正两处:

  1. 将我的 numberofsectionscode 更改为返回 1,这样我的第二张表就没有随机复制的第二部分

func numberOfSections(in tableView: UITableView) -> Int { 返回 1

  1. 添加新储蓄时用0替换该部分

//添加一个新的保存 let newIndexPath = IndexPath(row:SavingsDataModel.savings.count, section: 1)

关于ios - 更新 (15) 后现有部分中包含的行数必须等于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42915376/

有关ios - 更新 (15) 后现有部分中包含的行数必须等于的更多相关文章

  1. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  2. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

  3. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  4. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  5. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  6. ruby-on-rails - 在 heroku 的 .fonts 文件夹中包含自定义字体,似乎无法识别它们 - 2

    Heroku支持人员告诉我,为了在我的Web应用程序中使用自定义字体(未安装在系统中,您可以在bash控制台中使用fc-list查看已安装的字体)我必须部署一个包含所有字体的.fonts文件夹里面的字体。问题是我不知道该怎么做。我的意思是,我不知道文件名是否必须遵循heroku的任何特殊模式,或者我必须在我的代码中做一些事情来考虑这种字体,或者如果我将它包含在文件夹中它是自动的......事实是,我尝试以不同的方式更改字体的文件名,但根本没有使用该字体。为了提供更多详细信息,我们使用字体的过程是将PDF转换为图像,更具体地说,使用rghostgem。并且最终图像根本不使用自定义字体。在

  7. objective-c - 在设置 Cocoa Pods 和安装 Ruby 更新时出错 - 2

    我正在尝试为我的iOS应用程序设置cocoapods但是当我执行命令时:sudogemupdate--system我收到错误消息:当前已安装最新版本。中止。当我进入cocoapods的下一步时:sudogeminstallcocoapods我在MacOS10.8.5上遇到错误:ERROR:Errorinstallingcocoapods:cocoapods-trunkrequiresRubyversion>=2.0.0.我在MacOS10.9.4上尝试了同样的操作,但出现错误:ERROR:Couldnotfindavalidgem'cocoapods'(>=0),hereiswhy:U

  8. ruby-on-rails - Rails Associations 的更新方法是什么? - 2

    这太简单了,太荒谬了,我在任何地方都找不到关于它的任何信息,包括API文档和Rails源代码:我有一个:belongs_to关联,我开始理解当您没有关联时您在Controller中调用的正常模型方法与您有关联时调用的方法略有不同。例如,我的关联在创建Controller操作时运行良好:@user=current_user@building=Building.new(params[:building])respond_todo|format|if@user.buildings.create(params[:building])#etcetera但我找不到关于更新如何工作的文档:@user

  9. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  10. ruby-on-rails - Rails 3 在一个查询中包含多个表 - 2

    我正在为锦标赛开发一个Rails应用程序。我在这个查询中使用了三个模型:classPlayertruehas_and_belongs_to_many:tournamentsclassTournament:destroyclassPlayerMatch"Player",:foreign_key=>"player_one"belongs_to:player_two,:class_name=>"Player",:foreign_key=>"player_two"在tournaments_controller的显示操作中,我调用以下查询:Tournament.where(:id=>params

随机推荐