在UICollectionViewController(Swift 4)中实现UISearchBarController?

时间:2018-03-22 17:33:40

标签: swift uicollectionview uicollectionviewcell uisearchcontroller

我试图在UICollectionViewController中实现UISearchBarController,下面是代码:

    class FirstViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UISearchResultsUpdating {

         var titles: [String] = []

         var card: [RecommendArticles]?

         var searchArr = [String](){
            didSet {
               self.collectionView?.reloadData()
        }
    }

        func updateSearchResults(for searchController: UISearchController) {

            guard let searchText = searchController.searchBar.text else {
                return
            }

            searchArr = titles.filter { (title) -> Bool in
                return title.contains(searchText)
            }


        }


        let searchController = UISearchController(searchResultsController: nil)

       override func viewDidLoad() {

        super.viewDidLoad()

        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        navigationItem.hidesSearchBarWhenScrolling = true
        self.navigationItem.searchController = searchController
 }


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

        if (searchController.isActive) {
            return searchArr.count
        } else {
             return self.counters
        }

    }

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: verticalCellId, for: indexPath) as! VerticalCellId
        if (searchController.isActive) {
            cell.titleLabel.text = searchArr[indexPath.row]
            return cell
        } else {
            if let link = self.card?[indexPath.item]._imageURL {
                let url = URL(string: link)
                cell.photoImageView.kf.setImage(with: url)
            }

            if let title = self.card?[indexPath.item]._title {
                cell.titleLabel.text = title
                titles.append(title)
                print("\(titles)")
            }

            if let source = self.card?[indexPath.item]._source {
                cell.sourceLabel.text = source
            }

            return cell

        }




    }

以下是错误定位:

                titles.append(title)
                print("\(titles)")

当我搜索关键字时,过滤后的结果不正确,因为集合视图单元格将动态更改(我不确定我的表达式是否准确)。

但是,如果我像这样设置变量 titles ,它就可以完美运行:

var titles = ["Tom","Jack","Lily"]

但我必须从互联网上检索 标题 的值。任何建议将不胜感激。

以下是在self.card之后创建数组的更新问题:

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)

        self.view.addSubview(activityView)
        activityView.hidesWhenStopped = true
        activityView.center = self.view.center
        activityView.startAnimating()

        let dynamoDbObjectMapper = AWSDynamoDBObjectMapper.default()
        dynamoDbObjectMapper.load(TheUserIds2018.self, hashKey: "TheUserIds2018", rangeKey: nil, completionHandler: { (objectModel: AWSDynamoDBObjectModel?, error: Error?) -> Void in
            if let error = error {
                print("Amazon DynamoDB Read Error: \(error)")
                return
            }

            DispatchQueue.main.async {
                if let count = objectModel?.dictionaryValue["_articleCounters"] {
                    self.counters = count as! Int
                    self.collectionView?.reloadData()
                    self.updateItems()
                    self.activityView.stopAnimating()
                }

            }

        })

    }



 func updateItems() {
        let dynamoDbObjectMapper = AWSDynamoDBObjectMapper.default()
        var tasksList = Array<AWSTask<AnyObject>>()
        for i in 1...self.counters {
            tasksList.append(dynamoDbObjectMapper.load(RecommendArticles.self, hashKey: "userId" + String(self.counters + 1 - i), rangeKey: nil))
        }
        AWSTask<AnyObject>.init(forCompletionOfAllTasksWithResults: tasksList).continueWith { (task) -> Any? in
            if let cards = task.result as? [RecommendArticles] {
                self.card = cards
                DispatchQueue.main.async {
                if let totalCounts = self.card?.count {
                    for item in 0...totalCounts - 1 {
                        if let title = self.card?[item]._title {
                            self.newTitle = title
                        }
                        self.titles.append(self.newTitle)
                        print("titles: \(self.titles)")
                    }
                }
        }


            } else if let error = task.error {
                print(error.localizedDescription)
            }

            return nil

        }

    }

1 个答案:

答案 0 :(得分:2)

这不是UISearchController的问题。这与您的数据有关。集合视图数据源方法 -

cellForItemAtIndexPath仅在视图中显示单元格时有效。因此,您无法保留用于在cellForItemAtIndexPath

中创建标题数组的代码

您可以使用以下代码直接过滤self.card数组中带有搜索文字的数组,而不是单独保留数组中的标题字符串

self.searchArr = self.card?.filter(NSPredicate(format:"_title CONTAINS[cd] %@",searchText)).sorted(byKeyPath: "_title", ascending: true)

您可以在加载集合视图之前创建标题数组 创建self.card

后的某些位置