以上ios 7的横向搜索栏未显示全宽

以上ios 7的横向搜索栏未显示全宽,ios,objective-c,searchbar,Ios,Objective C,Searchbar,我最近在一个git hub项目中关注了集合视图搜索栏。其中有一个搜索栏,集合视图单元格。所有这些都在potrait模式下运行良好。当我使用横向模式查看时,屏幕上的搜索栏单独显示一半宽度的大小。这是搜索栏代码。我通过编程添加搜索栏 注意:我使用的部署目标7.0应在所有版本的ios 7,8,9设备中运行。 如何在横向模式下使我的搜索栏具有相同的宽度和高度以及全宽。 我的代码: #import "CollectionViewController.h" #import "CollectionViewCe

我最近在一个git hub项目中关注了集合视图搜索栏。其中有一个搜索栏,集合视图单元格。所有这些都在potrait模式下运行良好。当我使用横向模式查看时,屏幕上的搜索栏单独显示一半宽度的大小。这是搜索栏代码。我通过编程添加搜索栏

注意:我使用的部署目标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 =@[@"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);
    }
}
#导入“CollectionViewController.h”
#导入“CollectionViewCell.h”
@接口集合ViewController()
@属性(非原子,强)NSArray*数据源;
@属性(非原子,强)NSArray*dataSourceForSearchResult;
@属性(非原子)BOOL searchBarActive;
@性质(非原子)浮点数;
@属性(非原子,强)UISearchBar*搜索栏;
@属性(非原子,强)UIRefreshControl*refreshControl;
@结束
@实现集合视图控制器
静态NSString*const reuseIdentifier=@“Cell”;
-(无效)viewDidLoad{
[超级视图下载];
//加载视图后执行任何其他设置。
//用户在collectionView中搜索时使用的数据源
self.dataSourceForSearchResult=[NSArray new];
//正常数据源
self.dataSource=@[@“Modesto”、“Rebecka”、“Andria”、“Sergio”];
}
-(无效)视图将显示:(BOOL)动画{
[超级视图将显示:动画];
[自我准备];
}
-(无效)解除锁定{
//删除我们的KVO观察器
[自我反思的观察者];
}
-(无效)未收到记忆警告{
[超级记忆警告];
//处置所有可以重新创建的资源。
}
#pragma标记-动作
-(无效)重新制定合同{
[自我搜索];
在(调度时间(现在调度时间,(int64_t)(每秒2*NSEC_)),调度获取主队列()之后调度^{
//2秒后停止刷新
[self.collectionView-reloadData];
[自我刷新控制结束刷新];
});
}
#布拉格标记-
-(NSInteger)collectionView中的节数:(UICollectionView*)collectionView{
返回1;
}
-(NSInteger)collectionView:(UICollectionView*)collectionView项目编号截面:(NSInteger)截面{
如果(self.searchBarActive){
返回self.dataSourceForSearchResult.count;
}
返回self.dataSource.count;
}
-(UICollectionViewCell*)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath*)indexPath{
CollectionViewCell*cell=[collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
//配置单元格
如果(self.searchBarActive){
cell.laName.text=self.dataSourceForSearchResult[indexPath.row];
}否则{
cell.laName.text=self.dataSource[indexPath.row];
}
返回单元;
}
#布拉格标记-
-(UIEdgeInsets)collectionView:(UICollectionView*)collectionView
布局:(UICollectionViewLayout*)collectionViewLayout
插入方向索引:(NSInteger)部分{
返回UIEdgeInsetsMake(self.searchBar.frame.size.height,0,0,0);
}
-(CGSize)collectionView:(UICollectionView*)collectionView
布局:(UICollectionViewLayout*)collectionViewLayout
SizeFormitedIndeXPath:(NSIndexPath*)indexPath{
CGFloat cellLeg=(self.collectionView.frame.size.width/2)-5;
返回CGSizeMake(cellLeg,cellLeg);;
}
#pragma标记-搜索
-(void)filterContentForSearchText:(NSString*)搜索文本范围:(NSString*)范围{
NSPredicate*resultPredicate=[NSPredicate predicateWithFormat:@“self contains[c]@”,searchText];
self.dataSourceForSearchResult=[self.dataSource filteredArrayUsingPredicate:resultPredicate];
}
-(无效)搜索栏:(UISearchBar*)搜索栏文本更改:(NSString*)搜索文本{
//用户确实键入了一些内容,请检查数据源中是否有看起来相同的文本
如果(searchText.length>0){
//搜索并重新加载数据源
self.searchBarActive=是;
[self-filterContentForSearchText:searchText
范围:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
选择范围按钮索引]]];
[self.collectionView-reloadData];
}否则{
//如果文本长度==0
/我们将考虑搜索栏不是活动的。
self.searchBarActive=否;
}
}
-(无效)搜索栏取消按钮选中:(UISearchBar*)搜索栏{
[自我搜索];
[self.collectionView-reloadData];
}
-(无效)搜索栏搜索按钮选中:(UISearchBar*)搜索栏{
self.searchBarActive=是;
[自视图编辑:是];
}
-(无效)searchBarTextDidBeginEditing:(UISearchBar*)搜索栏{
//我们在这里设置self.searchBarActive=YES
//但我们不会再这样做了…它制造了问题
//当用户键入内容时,最好将self.searchBarActive设置为YES
[self.searchBar设置ShowScanCell按钮:是动画:是];
}
-(无效)SearchBartextdendediting:(UISearchBar*)搜索栏{
//点击键盘中的搜索btn时调用此方法
//我们设置searchBarActive=NO
//但无需重新加载CollectionView
self.searchBarActive=否;
[self.searchBar设置ShowScanCell按钮:否动画:是];
}
-(无效)取消搜索{
self.searchBarActive=否;
[self.searchBar辞职FirstResponder];
self.searchBar.text=@;
}
#pragma标记-prepareVC
-(无效)准备{
[自动添加搜索栏];
[自我控制];
}
-(无效)添加搜索栏{
如果(!self.searchBar){
self.searchBarBoundsY=self.navigationController.navigationBar.frame.size.height+[UIApplication sharedApplic
[[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;
}
-(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];
    }
}