[英]Sorting custom table view cells in Swift
我正在做一個小項目,我有一個應用程序可以接收用戶輸入的電視節目信息並將其顯示在自定義 tableview 單元格中。 我想根據用戶正在播放的當前劇集對節目進行排序。 我知道這段代碼是有效的,因為我用 print 語句對其進行了測試,它對數組進行了排序,但在模擬器上卻沒有進行排序。 所以我很好奇我應該把它放在哪里,以便它在應用程序端排序。
func sortShows() {
let sortedShows = tvShows.sorted { $0.currentEpisode > $1.currentEpisode}
TVShowTableView.reloadData()
print(sortedShows)
}
這是我目前將其放置在我的視圖中的位置 controller
extension TVShowListViewController: AddTVShowDelegate {
func tvShowWasCreated(tvShow: TVShow) {
tvShows.append(tvShow)
dismiss(animated: true, completion: nil)
TVShowTableView.reloadData()
sortShows()
}
}
在這部分代碼中:
func sortShows() {
// here you are creating a NEW array
let sortedShows = tvShows.sorted { $0.currentEpisode > $1.currentEpisode}
// here you tell the table view to reload with the OLD array
TVShowTableView.reloadData()
print(sortedShows)
}
在你的 controller class 中,你可能有這樣的東西:
var tvShows: [TVShow] = [TVShow]()
然后你用節目填充它,就像你用一個新節目一樣:
tvShows.append(tvShow)
然后你的 controller 正在做類似的事情:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tvShowCell", for: indexPath) as! TVShowCell
cell.tvShow = tvShows[indexPath.row]
return cell
}
您要做的是向您的 class 添加另一個變量:
var sortedShows: [TVShow] = [TVShow]()
然后更改您的排序功能以使用該數組:
func sortShows() {
// use the existing class-level array
sortedShows = tvShows.sorted { $0.currentEpisode > $1.currentEpisode}
// here you tell the table view to reload
TVShowTableView.reloadData()
print(sortedShows)
}
並更改您的其他功能以使用sortedShows
數組:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// use sortedShows array
return sortedShows.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tvShowCell", for: indexPath) as! TVShowCell
// use sortedShows array
cell.tvShow = sortedShows[indexPath.row]
return cell
}
並且您需要在viewDidLoad()
的末尾調用sortShows()
) (或者在您獲得初始節目列表的任何地方)。
編輯
您可以使用cellForRowAt
的另一種方式:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tvShowCell", for: indexPath) as! TVShowCell
// use sortedShows array
let tvShow = sortedShows[indexPath.row]
cell.showTitleLable.text = tvShow.title
cell.showDecriptionLable.text = tvShow.description
return cell
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.