【问题标题】:Insert new rows in tableView in iOS在 iOS 的 tableView 中插入新行
【发布时间】:2017-04-23 08:25:20
【问题描述】:

我正在用 Swift 编写一个 iOS 应用程序。

每当页面加载时,它都会从服务器获取电影列表并将该列表填充到tableView

我在静态库 (Objective-C) 中编写了从服务器获取 JSON 的代码,并通过通知设计模式将 json 接收到应用程序。

  override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(ReceivedNListOfMoviesNotification(_:)), name: Notification.Name(VUSDK.basicNotificationName()), object: nil)
    requestForData() 
  }

  func ReceivedNListOfMoviesNotification(_ notification:NSNotification)
  {
      if let info = notification.userInfo {         
        basicArray=info["Search"] as! [Any]
        if basicArray.count>0 {
            tableView.beginUpdates()
            self.tableView.insertRows(at: [IndexPath.init(row: self.basicArray.count-1, section: 0)], with: .automatic)                    
            tableView.endUpdates()
        }
      }
   }

但是应用程序崩溃了:

*** -[UITableView _endCellAnimationsWithContext:] 中的断言失败,/BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3600.7.47/UITableView.m:1737 2017-04-23 13:49:12.562 VUDemo[4835:164247] *** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无效更新:第 0 节中的行数无效。包含在更新后的现有节 (10) 必须等于更新前该节中包含的行数 (0),加上或减去从该节插入或删除的行数(1 插入,0 删除),加上或减去移入或移出该部分的行数(0 移入,0 移出)。'

【问题讨论】:

  • 在数据源数组的哪里添加对应的项?您有 first 将项目插入数据源数组,然后 then 插入该行。顺便说一句:删除 begin- / endUpdates 行。它们没有效果。
  • basicArray=info["Search"] as! [任何]
  • 在这种情况下不要调用insert...。请致电tableView.reloadData()
  • 请检查项目,我想增量重新加载数据,即每次用户滚动到tableView底部时从服务器获取数据

标签: ios swift uitableview


【解决方案1】:

替换

   if basicArray.count>0 {
        tableView.beginUpdates()

        self.tableView.insertRows(at: [IndexPath.init(row: self.basicArray.count-1, section: 0)], with: .automatic)

        tableView.endUpdates()
   }

   if !basicArray.isEmpty {
       tableView.reloadData()
   }

因为您要覆盖整个数组而不是添加单个项目。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    相关资源
    最近更新 更多