2017-05-24 7 views
0

나는이 문제를 몇 시간 동안 풀려고했으나 적절한 해결책을 찾지 못했습니다. 머리글에 세그먼트 컨트롤이있는 사용자 지정 UICollectionView가 있어야합니다. 세그먼트 화 된 제어 색인을 변경하면 셀이 다르게 렌더링됩니다. 지금까지는 내 collectionView의 머리글에 세그먼트 컨트롤을 표시 할 수 있지만 내 UserSearchHeader 내부의 collectionView 내용을 변경하면 작동하지 않습니다.Swift에서 헤더의 분할 된 컨트롤로 UICollectionView의 내용을 변경

UICollectionView의 서브 클래스이고 UICollectionViewDelegateFlowLayout 프로토콜을 준수하는 UserSearchController이라는 사용자 지정 UICollectionView를 만들었습니다.

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

내 사용자 정의 collectionView UserSearchController은 사용자 정의 헤더 (UserSearchHeader) 및 사용자 정의 세포 (UserSearchCell)가 있습니다.

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

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 
}() ..... 

segmentedIndex 내가 segmentedIndex 내가 (세그먼트 컨트롤을 클릭) 다른 cellClass으로 렌더링 할 일 경우 UserSearchCell 클래스와 세포를 렌더링 할 0 인 경우

. 이러한 여러 클래스를 사용하여이 동작을 어떻게 수행 할 수 있습니까? UserSearchController 내부의 메소드에서 cellForItem을 사용하여 세그먼트 화 된 컨트롤의 상태를 점검해야한다. 그러나 어떻게 세그먼트 화 된 컨트롤이 UserSearchHeader 클래스에 정의되어있을 때이 작업을 수행 할 수 있습니다.

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

네, 당신이 쉽게 수행 할 수 있습니다. 선택한 색인을 변경 한 후에 콜렉션 뷰를 다시로드해야합니다. 그리고 셀 인덱스에서 셀을 선택하십시오. 선택된 인덱스가 0인지 확인하십시오. cell2 –

+0

이 시도했는데 segmentedControl UserSearchHeader 정의되어 있기 때문에이 작동하지 않습니다.분할 된 컨트롤의 targetAction이 실행되지 않기 때문에 내용이 변경되지 않습니다. –

+0

그런 다음 선택한 인덱스 변경을 알리고 선택한 인덱스도 전달하는 프로토콜을 만듭니다. –

답변

0

scopeButtonTitles 속성을 사용해 보셨습니까?

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

자세한 내용은 this question을 참조하십시오. 처음에 제공된 링크에서 설명 빠진 부분을 검색 : 기본적으로 당신은

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를 사용합니다. NIB에서 헤더를 추가 할 필요가 없습니다.

먼저, 당신은 당신의 검색 & 결과 컨트롤러의 속성을 추가 :

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

그런 viewDidLoad에 당신이 추가

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

그런 다음 당신은 당신의 클래스에이 기능을 추가해야합니다

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 
} 

마지막으로 나는 처음에 설명했다 : searchBar:selectedScopeButtonIndexDidChange:

+0

내 searchBar가 내 navigationBar 안에 있고 scopeButtonTitles 속성을 추가 할 때 회색 배경이 표시되지 않습니다. –

+0

검색 모음을 내 collectionView의 머리글에 넣으면 다른 클래스에 다시 있는데 액세스 할 수 없습니다. 네비게이션 바 내부에 searchBar 위의 scopeButtonTiles를 어떻게 표시 할 수 있습니까? 네비게이션 바의 높이를 자동으로 높이려면 어떻게해야합니까? –

+0

UISearchController의 속성을 확인하십시오. 내 예제에서는 mySearchController라고합니다. 보시다시피 searchBar 속성은 네비게이션 바의 속성입니다. UISearchController의 속성 이름과 searchBar를 추가하는 방법을 살펴보십시오. 제공된 링크에는 예제가 있습니다. searchBar를 추가하는 것이 한 줄짜리이기 때문에 살펴보십시오. – pesch