2017-04-12 89 views
1

后我有一个UICollectionView这需要一个API搜索的结果。搜索由以下代码触发。结果被附加到字典[[String: Any]],我在查询完成后致电self.collectionView.reloadData()UICollectionView reloadData()崩溃emtying数据源字典

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 

    var newValue = textField.text! 
    let location = min(range.location, newValue.characters.count) 
    let startIndex = newValue.characters.index(newValue.startIndex, offsetBy: location) 
    let endIndex = newValue.characters.index(newValue.startIndex, offsetBy: location + range.length) 
    let newRangeValue = Range<String.Index>(startIndex ..< endIndex) 
    newValue.replaceSubrange(newRangeValue, with: string) 

    searchView.searchFieldValueChanged(newValue) 

    return true 
} 

然后,如果我想改变搜索字符串并重新搜索我要清空字典,并调用reloadData()我又得到一个应用程序崩溃。

的错误是

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UICollectionView received layout attributes for a cell with an index path that does not exist: 

这里是我的DataSource实现

var searchResults = [[String: Any]]() 


    let layout: UICollectionViewFlowLayout = { 
     let layout = UICollectionViewFlowLayout() 
     layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) 
     layout.estimatedItemSize.height = 200 
     layout.estimatedItemSize.width = 200 
     layout.minimumInteritemSpacing = 10 
     layout.minimumLineSpacing = 10 
     return layout 
    }() 

    collectionView = UICollectionView(frame: self.frame, collectionViewLayout: layout) 
    collectionView.delegate = self 
    collectionView.dataSource = self 
    collectionView.register(LanesCollectionViewCell.self, forCellWithReuseIdentifier: cellId) 
    collectionView.backgroundColor = .yellow // Constants.APP_BACKGROUND_COLOR 
    collectionView.alwaysBounceVertical = true 
    collectionView.clipsToBounds = true 
    collectionView.translatesAutoresizingMaskIntoConstraints = false 

func numberOfSections(in collectionView: UICollectionView) -> Int { 

    return 1 
} 


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 

    if searchResults.count == 0 { 
     collectionView.alpha = 0.0 
    } else { 
      collectionView.alpha = 1.0 
    } 
    return searchResults.count 
} 

查询

func parseMoreData(jsonData: [String: Any]) { 

    let items = jsonData["items"] as! [[String: Any]] 

     self.collectionView.layoutIfNeeded() 

     self.collectionView.reloadData() 
    } 
} 

func searchFieldValueChanged(_ textValue: String) { 

    searchResults = [] 
+0

请问您可以分享您的'collectionView'的'dataSource'实现的代码吗? – dirtydanee

+0

代替使用reloadData()尝试使用reloadSections – Neha

+0

为数据源添加了额外的代码。只有一个部分。 – markhorrocks

回答

0

这看起来用这个代替的layoutIfNeeded()

固定后210
collectionView.reloadData() 

collectionView.collectionViewLayout.invalidateLayout()