string、url、intの値を使用してクラスを作成し、チャネル配列を作成しましたが、チャネル配列を適切にフィルタリングできません。
これは私のクラスです:
class Channel {
var name: String
var url: URL
var icon: URL?
var priority: Int
init(name:String, url:URL, icon:URL?, priority:Int) {
self.name = name
self.url = url
self.icon = icon
self.priority = priority
}
}
私はこの機能を試していましたが、機能しません!
public var channels: [Channel] = []
var filteredData = [Channel]()
var searching = false
...
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if searching {
return filteredData.count
}
return channels.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let channel = channels[indexPath.item] as Channel? {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? CollectionViewCell {
if searching {
cell.name.text = filteredData[indexPath.row].name
print("fil \(filteredData[indexPath.row].name)")
} else {
cell.name.text = channel.name
print("not \(channel.name)")
}
if let iconUrl = channel.icon {
cell.icon.cacheSetImageFromURL(iconUrl)
} else {
cell.icon.image = #imageLiteral(resourceName: "tv1600")
}
return cell
}
}
return UICollectionViewCell()
}
...
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
searching = false
collectionView.reloadData()
}else{
print("searching")
searching = true
filteredData = channels.filter({$0.name.lowercased().prefix(searchText.count) == searchText.lowercased()})
collectionView.reloadData()
}
}
期待される結果は、ColctionViewの既存のコンテンツを含むフィルター処理された配列を示しています。
cellForItemAt
以下のように更新します。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
let channel = self.searching ? filteredData[indexPath.row] : channels[indexPath.item]
cell.name.text = channel.name
print("fil \(channel.name)")
if let iconUrl = channel.icon {
cell.icon.cacheSetImageFromURL(iconUrl)
} else {
cell.icon.image = #imageLiteral(resourceName: "tv1600")
}
return cell
}
このline(if let channel = channels[indexPath.item] as Channel? {
)は、channel
検索中でもすべての要素を含むフィルター処理されていない配列から常にオブジェクトを取得するという問題を引き起こしています。したがって、を正しく表示channel
するにはarray
、上記の対応するオブジェクトからオブジェクトを取得する必要がありますresults
。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加