Swift3 UICollectionView重载数据()在绑定数据源字典后崩溃
我有一个Swift3 UICollectionView重载数据()在绑定数据源字典后崩溃,swift3,uicollectionview,Swift3,Uicollectionview,我有一个UICollectionView,它获取API搜索的结果。搜索由以下代码触发。结果被附加到字典[[String:Any]],查询完成后我调用self.collectionView.reloadData() func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { var newVa
UICollectionView
,它获取API搜索的结果。搜索由以下代码触发。结果被附加到字典[[String:Any]]
,查询完成后我调用self.collectionView.reloadData()
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
}
这是我的数据源实现
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 = []
通过使用此选项而不是
layoutIfNeeded()
请共享您的
集合视图
的数据源
实现的代码,而不是使用重载数据()尝试使用重载部分为数据源添加额外代码。这里只有一个部分。您是否将API响应添加到searchResults中,并从主线程中通知新单元格的集合视图?我相信是的,我没有使用过任何异步线程,除了Alamofire,它在内部使用异步线程。这对我很有效,谢谢。看起来这个问题在iOS 11中已经解决了。
func parseMoreData(jsonData: [String: Any]) {
let items = jsonData["items"] as! [[String: Any]]
self.collectionView.layoutIfNeeded()
self.collectionView.reloadData()
}
}
func searchFieldValueChanged(_ textValue: String) {
searchResults = []
collectionView.reloadData()
collectionView.collectionViewLayout.invalidateLayout()