Ios 在TableView中插入行
我通过JSON获取数据,当我滚动屏幕时,我向服务器发出一个请求,有时数据可能会结束,然后应用程序在Ios 在TableView中插入行,ios,iphone,swift,uitableview,Ios,Iphone,Swift,Uitableview,我通过JSON获取数据,当我滚动屏幕时,我向服务器发出一个请求,有时数据可能会结束,然后应用程序在insertRows上崩溃,我如何修复它 这是我的代码: override func scrollViewDidScroll(_ scrollView: UIScrollView) { if (!isMoreDataLoading) { let down = "https://--.com/local/apps/apple/events.php/?nPageSize=\(
insertRows
上崩溃,我如何修复它
这是我的代码:
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (!isMoreDataLoading) {
let down = "https://--.com/local/apps/apple/events.php/?nPageSize=\(nPageSize)&iNumPage=\(iNumPage)"
let scrollViewContentHeight = tableView.contentSize.height
let scrollOffsetThreshold = scrollViewContentHeight - tableView.bounds.size.height
if(scrollView.contentOffset.y > scrollOffsetThreshold && tableView.isDragging) {
isMoreDataLoading = true
requestD(url: down)
}
}
}
func requestD(url:String){
var urlRequest = URLRequest(url: URL(string: url)!)
urlRequest.timeoutInterval = 300
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil{
print(error ?? 0)
return
}
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
if let newsJson = json["EVENTS"] as? [[String : AnyObject]] {
for newJson in newsJson{
let info = Modal()
info.id = newJson["ID"] as? String
info.name = newJson["NAME"] as? String
if newJson["PICTURE"] as? String != nil {
info.ImageViewURL = newJson["PICTURE"] as! String
}
if newJson["PICTURE_DETAIL"] as? String != nil {
info.ImageViewURLDetail = newJson["PICTURE_DETAIL"] as! String
}
info.stmp = newJson["STMP"] as? Int
info.text = newJson["DETAIL_TEXT"] as? String
info.name = info.name?.replacingOccurrences(of: "&[^;]+;", with: "", options: String.CompareOptions.regularExpression, range: nil)
info.text = info.text?.replacingOccurrences(of: "&[^;]+;", with: "", options: String.CompareOptions.regularExpression, range: nil)
if self.isRefresh == true {
self.modals.insert(info, at: 0)
} else {
self.modals.append(info)
}
}
}
} catch let error {
print(error)
}
DispatchQueue.main.sync {
self.iNumPage += 1
self.isMoreDataLoading = false
self.Preload.preloadEnd(tableView: self.tableView)
// self.tableView.reloadData()
self.tableView.beginUpdates()
self.tableView.insertRows(at: [IndexPath(row: self.modals.count - 1, section: 0)], with: .automatic)
self.tableView.endUpdates()
}
}
task.resume()
}
原因:
“无效更新:节0中的行数无效。”。更新后现有节中包含的行数(5)必须等于更新前该节中包含的行数(0),加上或减去从该节中插入或删除的行数(1插入,0删除),加上或减去移入或移出该节的行数(0移入,0移出).
如果要在tableView中删除/插入元素,则需要执行以下操作:
设置新表行时,并没有在数组中添加新数据。
添加此代码
self.modals.insert(,atIndex:yourIndex)
在表中插入新行之前。并尝试删除DispatchQueue崩溃消息是什么?@Paulw11问题原因您不理解我的问题。如果用户向下滚动到要添加新行的do块中的更新表时没有数据,我需要锁定,因为数据任务需要时间,插入表正在调用两个代码都不同步,你的表插入代码没有等待数据来发现问题。如果我上传5条新闻,那么它会给出相同的错误。
anArray.insert("This String", atIndex: indexPath.row)
tableView.reloadData()