首页 > 解决方案 > 未找到搜索结果时添加带有标签的背景视图

问题描述

当没有找到搜索结果时,我正在尝试添加背景视图。我已经阅读了这个网站上的几个问题/答案,但没有一个有效。我希望背景视图在结果计数等于 0 时显示“无搜索结果”。

这是我尝试过的:

var filmsTable: UICollectionView!
var backgroundView: UIView?

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    if searchText == "" {
        self.filteredFilms = films
        self.filmsTable.reloadData()
    } else {
        self.filteredFilms = films!.filter({(($0["title"] as! String).lowercased().contains(searchText.lowercased()))})
        //print(self.filteredFilms!.count)

if self.filteredFilms!.count == 0 {
let emptyLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.filmsTable.frame.width, height: self.filmsTable.frame.height))
    emptyLabel.text = "No Search Results"
    emptyLabel.textColor = .black
    emptyLabel.numberOfLines = 0;
    emptyLabel.textAlignment = .center;
    emptyLabel.font = UIFont(name: "Times", size: 18)
    emptyLabel.sizeToFit()

    self.backgroundView = emptyLabel;
}
        self.filmsTable.reloadData()
    }
}

标签: iosswiftuicollectionview

解决方案


我想你是在运行中设置的backgroundView,你可以试试

self.filmsTable.backgroundView = emptyLabel

如果 name 是也更有意义filmsCollection


推荐阅读