Панель поиска не отображается во всю ширину в альбомной ориентации для выше ios 7

Недавно я следил за одним проектом git hub для панели поиска представления коллекции. В ней есть панель поиска, ячейка представления коллекции. Все хорошо работает в портретном режиме. Когда я использую ландшафтный режим, чтобы увидеть, только панель поиска на экране показывает размер половинной ширины. Вот штрих-код поиска. Я использую программно, чтобы добавить панель поиска.

ПРИМЕЧАНИЕ. Я использую цель развертывания 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);
    }
}

Также полный проект можно получить здесь Git-hub

Вот изображение в портретном режиме:

введите здесь описание изображения

Эта же панель поиска, когда я запускаю пейзаж моего морявведите описание изображения здесьправая полоса разделена пополам вот так:

Какой код мне нужно добавить, чтобы установить панель поиска с полноразмерным видом в ландшафтном режиме. Спасибо!


person user5513630    schedule 04.11.2015    source источник
comment
Как вы относитесь к использованию ограничений? Это решило бы ее без написания кода с использованием класса размера.   -  person gikygik    schedule 05.11.2015
comment
s bro. Но я не знаю о добавлении программных ограничений для панели поиска ... теперь это проблема. я пытался добавить но выдает ошибку   -  person user5513630    schedule 05.11.2015


Ответы (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;
}
person Piyush Sharma    schedule 04.11.2015
comment
я добавил ваш код в case case UIDeviceOrientationLandscapeLeft:Но моя панель поиска не заполнила пространство в альбомной ориентации - person user5513630; 05.11.2015
comment
на самом деле моя цель развертывания, которую я установил как 7.0. Итак, теперь, какой из них я должен использовать, чтобы моя панель поиска выглядела полностью в ландшафтном режиме для всех версий ios7,8,9 - person user5513630; 05.11.2015
comment
Хорошо, тогда мы будем искать другое решение для вашей проблемы. - person Piyush Sharma; 05.11.2015
comment
пожалуйста, используйте мою ссылку на git hub, чтобы увидеть добавление каких-либо ограничений, или мне нужно изменить значение ширины в каком-то месте. Я тоже пытался купить, но не могу получить - person user5513630; 05.11.2015
comment
Обновленный ответ, и теперь он отлично работает в вашем проекте Github. - person Piyush Sharma; 05.11.2015
comment
у меня есть один вопрос ........ Если я установлю цель развертывания как 7.0 - тогда, если я запущу свое приложение на устройстве, которое работает в ios 7, 8, 9, мое приложение будет работать хорошо .. - person user5513630; 05.11.2015
comment
Не для цели развертывания, братан. - person user5513630; 05.11.2015
comment
мое приложение полностью развертывается как 7.0..будет ли оно работать на всех устройствах, которые работают в ios 7,8,9 - person user5513630; 05.11.2015
comment
Да, это будет !! Просто не забудьте удалить наблюдателя либо для viewDidUnload, либо для viewWillDisappear. - person Piyush Sharma; 05.11.2015
comment
пожалуйста, посмотрите на этот пост у одного из моих коллег, у которого есть проблема stackoverflow .com/questions/33529452/ - person user5513630; 05.11.2015
comment
а также этот пост stackoverflow.com/questions/33527619/ - person user5513630; 05.11.2015
comment
братан, пожалуйста, помогите решить эту проблему в этой 2 ссылке, которую я отправил. Они работают с развертыванием как 9.0 - person user5513630; 05.11.2015
comment
Работаю только над вопросом SearchController, братан. - person Piyush Sharma; 05.11.2015
comment
да, это также предупреждение об использовании searchdisplaycontroller - person user5513630; 05.11.2015

Я использовал ваш проект в 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];
    }
}

Надеюсь, это поможет!

person Spike    schedule 04.11.2015