2015-11-04 53 views
1

我最近跟着一個git hub項目收集視圖搜索欄。在那裏有一個搜索欄,收藏視圖單元格。在potrait模式下一切正常。當我使用橫向模式查看時,單獨顯示半寬尺寸的屏幕搜索欄。這裏是搜索欄代碼。我使用編程方式添加搜索欄。搜索欄不能以橫向全寬顯示以上ios 7

注意:我使用的部署目標7.0應該運行在所有版本的ios 7,8,9設備上。

如何使我的搜索欄的寬度相同&橫向模式下的全寬度。

我的代碼:

#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"]; 

} 


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

還可以獲得完整的項目在這裏Git-hub

這裏肖像模式圖像:

enter image description here

,當我在景觀上運行同樣的搜索欄我海enter image description here rch酒吧是這樣一半:

我需要添加什麼代碼來設置我的搜索欄全景視圖橫向mode.Thnaks!

+0

您如何看待使用約束?這將解決它而無需使用大小類編寫任何代碼。 – gikygik

+0

s bro.But但我不知道爲搜索欄添加編程方式的限制..現在多數民衆贊成在一個問題。我試圖添加,但它會拋出錯誤 – user5513630

回答

2

嘗試做以下時,你的看法負載或出現:

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 
[[NSNotificationCenter defaultCenter] 
    addObserver:self selector:@selector(orientationChanged:) 
    name:UIDeviceOrientationDidChangeNotification 
    object:[UIDevice currentDevice]]; 

然後在您的視圖控制器添加下面的方法:

- (void) orientationChanged:(NSNotification *)note 
{ 
CGRect frame = _searchBar.frame; 
frame.size.width = self.view.frame.size.width; 
_searchBar.frame = frame; 
} 
+0

我在案例中添加了'case UIDeviceOrientationLandscapeLeft:'但是沒有我的搜索欄填充橫向空間 – user5513630

+0

iOS 8方法也沒有奏效? –

+0

實際上我的部署目標爲7.0。所以,現在我應該使用哪一個來實現我的搜索欄在橫向模式下全屏查看所有版本ios7,8,9 – user5513630

4

我已經用在GitHub的項目。讓我們做出改變工作全搜索欄在橫向模式下:替換下面的代碼,因爲它在你addsearchbar方法:

-(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"; 


    // added line-to set your screen fit and autoresizing with width and bottom margin.You can also add any position to that 

     [self.searchBar sizeToFit]; 

     _searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleBottomMargin; 

     [[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]; 
    } 
} 

希望這有助於!

+0

是的,它的工作很好都答案 – user5513630