首页 > 解决方案 > 防止搜索栏辞去第一响应者 SWIFT 4.2

问题描述

我的集合视图的标题中有一个搜索栏,我希望能够将内容过滤为用户类型。问题是,每次我在搜索栏的 textDidChange 事件中重新加载集合视图时,集合视图都会成为第一响应者,并且搜索栏会辞职,从而隐藏键盘。

我已经检查了所有答案;

UICollectionView reloadData 在部分标题中辞去第一响应者

如何过滤 UICollectionView 并保持键盘正常运行?

以及任何其他可能相关但没有找到答案的帖子。如果你们能提供帮助,我将非常高兴。

提前致谢

标签: uisearchbarcollectionviewswift4.2reloaddatabecomefirstresponder

解决方案


我找不到任何合适的解决方案来解决这个问题,所以我将搜索栏添加到我的主视图中,并将其高度值与我的集合视图 didscroll 事件同步。

如果有人感兴趣,这是代码片段。

    let offset = self.collectionView.contentOffset
    let y = offset.y

    if lastContentOffset > scrollView.contentOffset.y && lastContentOffset < scrollView.contentSize.height - scrollView.frame.height {
        // move up
        if self.cst_searchBarHeight.constant == 0 && y <= 0{
            self.cst_searchBarHeight.constant = self.searchBarHeight
            UIView.animate(withDuration: 0.4, delay: 0.0, options: [.curveEaseInOut], animations: {
                self.view.layoutIfNeeded()
            }, completion: nil)
        }

    } else if lastContentOffset < scrollView.contentOffset.y && scrollView.contentOffset.y > 0 {
        // move down
        if self.cst_searchBarHeight.constant != 0{
            self.cst_searchBarHeight.constant = 0
            UIView.animate(withDuration: 0.4, delay: 0.0, options: [.curveEaseInOut], animations: {
                self.view.layoutIfNeeded()
            }, completion: nil)
        }
    }
    // update the new position acquired
    lastContentOffset = scrollView.contentOffset.y
}

我从下面的答案中得到了想法,它找出了集合视图的滚动方向 如何检测 UICollectionView 的滚动方向?


推荐阅读