简体   繁体   English

在Swift的标头中使用分段控件更改UICollectionView的内容

[英]Changing content of UICollectionView with segmented Control in the header in Swift

I tried to solve this problem since hours and didn't find a proper solution. 我几个小时以来一直试图解决此问题,但没有找到合适的解决方案。 I want to have a custom UICollectionView with a segmented control in the header. 我想要一个自定义UICollectionView,标题中带有分段控件。 Changing the segmented control index should render the cells differently. 更改分段的控制索引应使单元格呈现不同的效果。 So far I can display the segmented control in the header of my collectionView but changing the content of the collectionView inside of my UserSearchHeader doesn't work. 到目前为止,我可以在collectionView的标题中显示分段的控件,但是无法在UserSearchHeader内更改collectionView的内容。

I created a custom UICollectionView called UserSearchController which is a Subclass of UICollectionView and conforms the UICollectionViewDelegateFlowLayout protocol. 我创建了一个名为UserSearchController的自定义UICollectionView,它是UICollectionView的子类,并且符合UICollectionViewDelegateFlowLayout协议。

        class UserSearchController: UICollectionViewController, 
              UICollectionViewDelegateFlowLayout, UISearchBarDelegate { ....

My custom collectionView UserSearchController has a custom header ( UserSearchHeader ) and custom cells ( UserSearchCell ). 我的自定义collectionView UserSearchController有一个自定义标头( UserSearchHeader )和自定义单元格( UserSearchCell )。

  collectionView?.register(UserSearchCell.self, forCellWithReuseIdentifier: cellId)
  collectionView?.register(UserSearchHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")

The UserSearchHeader contains the segmented control. UserSearchHeader包含分段的控件。

   class UserSearchHeader: UICollectionViewCell {

var segmentedControl: UISegmentedControl = {
    let sc = UISegmentedControl(items: ["Username", "Hashtag"])
    sc.translatesAutoresizingMaskIntoConstraints = false
    sc.tintColor = UIColor.black
    sc.selectedSegmentIndex = 0 // automatically highlight
    //  sc.addTarget(self, action: #selector(segmentedChange), for: .valueChanged)
    return sc
}() .....

If the segmentedIndex is 0 I want to render the cells with the UserSearchCell class if the segmentedIndex is 1 I want to render it with a different cellClass (Clicking the segmented control). 如果segmentedIndex为0,我想用UserSearchCell类渲染单元格;如果segmentedIndex为1,我想用不同的cellClass渲染单元格(单击分段控件)。 How can I achieve this behavior with these different classes. 如何使用这些不同的类来实现此行为。 shall I use the cellForItem at method inside of the UserSearchController to check the status of the segmented control. 我应该在UserSearchController内部的方法上使用cellForItem来检查分段控件的状态。 But how can I do this when the segmented control is defined in the UserSearchHeader class . 但是,如果在UserSearchHeader类中定义了分段控件,该怎么办?

       override func collectionView(_ collectionView: 
    UICollectionView, cellForItemAt indexPath: IndexPath) -> 
  UICollect. ionViewCell { if segmentedControl.segmentedIndex = 0 ....}

tried using Use the scopeButtonTitles property? 尝试使用Use scopeButtonTitles属性?

mySearchController.searchBar.scopeButtonTitles = ["Username", "Hashtag"]

Have a look at this question for more details. 请查看此问题以获取更多详细信息。 Basically you use the 基本上,您使用

func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { 
    // respond to your scopeBar selection here
    switch selectedScope {
    case 0:
        print("Username tab selected")
        // do your stuff for Username here
    case 1:
        print("Hashtag tab selected")
        // do your stuff for Hashtag here
    default:
        print("Someone added a tab!")
        // you shouldn't have more than 2 tabs
}

EDIT: Please find below the missing pieces described in the link provided initially. 编辑:请在下面提供的最初提供的链接中找到丢失的部分。 There is no need to add the header from a NIB. 无需从NIB添加标头。

First, you add properties for your search & results controllers: 首先,为搜索和结果控制器添加属性:

typealias ResultVC = UserResultController //The class to show your results
var searchController: UISearchController! 
var resultController: ResultVC? 

Then, in viewDidLoad you add this: 然后,在viewDidLoad添加以下内容:

// Search Results 
resultController = ResultVC() 
setupSearchControllerWith(resultController!) 
if #available(iOS 9.0, *) { 
    searchController?.loadViewIfNeeded() 
} 

Then you need to add this function to your class: 然后,您需要将此函数添加到您的类中:

func setupSearchControllerWith(_ results: ResultVC) { 
    // Register Cells 
    results.tableView.register(TableCell.self, forCellReuseIdentifier: "\(TableCell.self)") 
    results.tableView.register(UINib(nibName: "\(TableCell.self)", bundle: Bundle.main), forCellReuseIdentifier: "\(TableCell.self)") 

  // We want to be the delegate for our filtered table so didSelectRowAtIndexPath(_:) is called for both tables. 
    results.tableView.delegate = self 

    searchController = UISearchController(searchResultsController: results) 

    // Set Scope Bar Buttons 
    searchController.searchBar.scopeButtonTitles = ["Comics only", "Digital too"] 

    // Set Search Bar 
    searchController.searchResultsUpdater = self 
    searchController.searchBar.sizeToFit() 
    tableView.tableHeaderView = searchController.searchBar 

    // Set delegates 
    searchController.delegate = self 
    searchController.searchBar.delegate = self    // so we can monitor text & scope changes 

    // Configure Interface 
    searchController.dimsBackgroundDuringPresentation = false 
    searchController.hidesNavigationBarDuringPresentation = true 
    if #available(iOS 9.1, *) { 
        searchController.obscuresBackgroundDuringPresentation = false 
    }  

    // Search is now just presenting a view controller. As such, normal view controller 
    // presentation semantics apply. Namely that presentation will walk up the view controller 
    // hierarchy until it finds the root view controller or one that defines a presentation context. 
    definesPresentationContext = true 
} 

Finally, you add the function I was describing initially: searchBar:selectedScopeButtonIndexDidChange: 最后,添加我最初描述的功能: searchBar:selectedScopeButtonIndexDidChange:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM