2015-11-02 73 views
2

我正在使用搜索欄的集合視圖。我已經通過鱈魚從(0,0)orgin從頂部添加搜索欄。所以現在我的形象是這樣的:如何在集合視圖的頂部下方添加標題部分

[![在這裏輸入的形象描述] [1] [1]

但我需要下面頭到我的搜索欄。我通過故事board.But而運行我的標題名稱&搜索欄是在相同orgin.I需要將我的標題部分放在myseaarch酒吧下面。

注:我唱3節header.any想法或代碼是非常有幫助ful。

這裏我搜索條碼...

#import "CollectionViewController.h" 
#import "CollectionViewCell.h" 
@interface CollectionViewController()<UISearchBarDelegate> 

    @property (nonatomic,strong) NSArray  *dataSource; 
    @property (nonatomic,strong) NSArray  *dataSourceForSearchResult; 
    @property (nonatomic)  BOOL   searchBarActive; 
    @property (nonatomic)  float   searchBarBoundsY; 

    @property (nonatomic,strong) UISearchBar  *searchBar; 
    @property (nonatomic,strong) UIRefreshControl *refreshControl; 

@end 

@implementation CollectionViewController 

static NSString * const reuseIdentifier = @"Cell"; 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    // Do any additional setup after loading the view. 
    // datasource used when user search in collectionView 
    self.dataSourceForSearchResult = [NSArray new]; 

    // normal datasource 
    self.dataSource [email protected][@"Modesto",@"Rebecka",@"Andria",@"Sergio",@"Robby",@"Jacob",@"Lavera",@"Theola",@"Adella",@"Garry", @"Lawanda", @"Christiana", @"Billy", @"Claretta", @"Gina", @"Edna", @"Antoinette", @"Shantae", @"Jeniffer", @"Fred", @"Phylis", @"Raymon", @"Brenna", @"Gus", @"Ethan", @"Kimbery", @"Sunday", @"Darrin", @"Ruby", @"Babette", @"Latrisha", @"Dewey", @"Della", @"Dylan", @"Francina", @"Boyd", @"Willette", @"Mitsuko", @"Evan", @"Dagmar", @"Cecille", @"Doug", @"Jackeline", @"Yolanda", @"Patsy", @"Haley", @"Isaura", @"Tommye", @"Katherine", @"Vivian"]; 

} 


-(void)viewWillAppear:(BOOL)animated{ 
    [super viewWillAppear:animated]; 
    [self prepareUI]; 
} 
-(void)dealloc{ 
    // remove Our KVO observer 
    [self removeObservers]; 
} 
- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 


#pragma mark - actions 
-(void)refreashControlAction{ 
    [self cancelSearching]; 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 
     // stop refreshing after 2 seconds 
     [self.collectionView reloadData]; 
     [self.refreshControl endRefreshing]; 
    }); 
} 


#pragma mark - <UICollectionViewDataSource> 
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { 
    return 1; 
} 
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { 
    if (self.searchBarActive) { 
     return self.dataSourceForSearchResult.count; 
    } 
    return self.dataSource.count; 
} 
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath]; 

    // Configure the cell 
    if (self.searchBarActive) { 
     cell.laName.text = self.dataSourceForSearchResult[indexPath.row]; 
    }else{ 
     cell.laName.text = self.dataSource[indexPath.row]; 
    } 
    return cell; 
} 


#pragma mark - <UICollectionViewDelegateFlowLayout> 
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView 
         layout:(UICollectionViewLayout*)collectionViewLayout 
     insetForSectionAtIndex:(NSInteger)section{ 
    return UIEdgeInsetsMake(self.searchBar.frame.size.height, 0, 0, 0); 
} 
- (CGSize)collectionView:(UICollectionView *)collectionView 
        layout:(UICollectionViewLayout*)collectionViewLayout 
    sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ 
    CGFloat cellLeg = (self.collectionView.frame.size.width/2) - 5; 
    return CGSizeMake(cellLeg,cellLeg);; 
} 


#pragma mark - search 
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{ 
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"self contains[c] %@", searchText]; 
    self.dataSourceForSearchResult = [self.dataSource filteredArrayUsingPredicate:resultPredicate]; 
} 

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ 
    // user did type something, check our datasource for text that looks the same 
    if (searchText.length>0) { 
     // search and reload data source 
     self.searchBarActive = YES; 
     [self filterContentForSearchText:searchText 
            scope:[[self.searchDisplayController.searchBar scopeButtonTitles] 
              objectAtIndex:[self.searchDisplayController.searchBar 
                 selectedScopeButtonIndex]]]; 
     [self.collectionView reloadData]; 
    }else{ 
     // if text lenght == 0 
     // we will consider the searchbar is not active 
     self.searchBarActive = NO; 
    } 
} 

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{ 
    [self cancelSearching]; 
    [self.collectionView reloadData]; 
} 
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{ 
    self.searchBarActive = YES; 
    [self.view endEditing:YES]; 
} 
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{ 
    // we used here to set self.searchBarActive = YES 
    // but we'll not do that any more... it made problems 
    // it's better to set self.searchBarActive = YES when user typed something 
    [self.searchBar setShowsCancelButton:YES animated:YES]; 
} 
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{ 
    // this method is being called when search btn in the keyboard tapped 
    // we set searchBarActive = NO 
    // but no need to reloadCollectionView 
    self.searchBarActive = NO; 
    [self.searchBar setShowsCancelButton:NO animated:YES]; 
} 
-(void)cancelSearching{ 
    self.searchBarActive = NO; 
    [self.searchBar resignFirstResponder]; 
    self.searchBar.text = @""; 
} 
#pragma mark - prepareVC 
-(void)prepareUI{ 
    [self addSearchBar]; 
    [self addRefreshControl]; 
} 
-(void)addSearchBar{ 
    if (!self.searchBar) { 
     self.searchBarBoundsY = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height; 
     self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,self.searchBarBoundsY, [UIScreen mainScreen].bounds.size.width, 44)]; 
     self.searchBar.searchBarStyle  = UISearchBarStyleMinimal; 
     self.searchBar.tintColor   = [UIColor whiteColor]; 
     self.searchBar.barTintColor   = [UIColor whiteColor]; 
     self.searchBar.delegate    = self; 
     self.searchBar.placeholder   = @"search here"; 

     [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor whiteColor]]; 

     // add KVO observer.. so we will be informed when user scroll colllectionView 
     [self addObservers]; 
    } 

    if (![self.searchBar isDescendantOfView:self.view]) { 
     [self.view addSubview:self.searchBar]; 
    } 
} 

-(void)addRefreshControl{ 
    if (!self.refreshControl) { 
     self.refreshControl     = [UIRefreshControl new]; 
     self.refreshControl.tintColor  = [UIColor whiteColor]; 
     [self.refreshControl addTarget:self 
           action:@selector(refreashControlAction) 
         forControlEvents:UIControlEventValueChanged]; 
    } 
    if (![self.refreshControl isDescendantOfView:self.collectionView]) { 
     [self.collectionView addSubview:self.refreshControl]; 
    } 
} 
-(void)startRefreshControl{ 
    if (!self.refreshControl.refreshing) { 
     [self.refreshControl beginRefreshing]; 
    } 
} 

#pragma mark - observer 
- (void)addObservers{ 
    [self.collectionView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; 
} 
- (void)removeObservers{ 
    [self.collectionView removeObserver:self forKeyPath:@"contentOffset" context:Nil]; 
} 
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(UICollectionView *)object change:(NSDictionary *)change context:(void *)context{ 
    if ([keyPath isEqualToString:@"contentOffset"] && object == self.collectionView) { 
     self.searchBar.frame = CGRectMake(self.searchBar.frame.origin.x, 
              self.searchBarBoundsY + ((-1* object.contentOffset.y)-self.searchBarBoundsY), 
              self.searchBar.frame.size.width, 
              self.searchBar.frame.size.height); 
    } 
} 


@end 

回答

5

頭可以在故事板由屬性檢查器檢查下部分加入:

enter image description here

你還需要在您的收藏視圖數據源中實現以下方法:

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath]; 
    return view; 
} 

其中標識符也在標題的故事板中設置。

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section { 
    return CGSizeMake(0, 80); 
} 

這裏是連環畫的外觀:

enter image description here

您可能會遇到麻煩獲取正確的佈局,你是

頭高度可以通過委託方法來控制手動添加搜索欄。搜索欄可以添加到故事板中。如果您選擇在故事板中添加搜索欄,則必須重新構建視圖(包括您的集合視圖),以便將它們包含在父視圖中。否則,您必須手動操作約束條件以獲得搜索欄的正確位置。

+0

它似乎沒有辦法爲頁眉位置....我也儘量讓(10,70) - 但只有x位置不能正常工作...查看我更新的帖子 – 2131

+0

標題處於正確的位置,但是您添加的搜索欄干擾了佈局。我建議你安排你的觀點,因爲在這個帖子的接受答案https://stackoverflow.com/questions/25460764/how-to-add-searchbar-in-collectionview,以防止這種情況。 CGSize僅適用於高度,根據滾動方向僅使用一個值。由於您正在垂直滾動,因此只使用y值。 – Daniel

+0

但是我們在這裏以編程方式添加搜索欄,而不是通過故事板添加搜索欄來設置層級視圖,如接受的答案外觀。有沒有辦法在代碼中添加相同的層次結構視圖.... – 2131

3

@Daniel Zhang說,你是垂直滾動的。所以你不能使用x軸改變position.But你可以做一件事.....做的步驟:

1. Add the code @Daniel Zhang suggest and do 
2. In story board make the header size height = 80, then place the label over there. 

3. Then add constraint (i.e as you want where to place your header title).Then give background color for label. so that it will show different from your cell,searchbar. 
4. Make you cell top = 0. You can do when you click your collection view & move to size inspector. 

完蛋了,運行,看看你會看到你的頭有所不同,從細胞,搜索欄。

試試這個它me.If工作它din't work.Try看到這個demo project where they use search bar using story-board

相關問題