Измените кадр UISearchBar программно при изменении ориентации

У меня есть кнопка поиска, и когда пользователь нажимает ее, я программно отображаю UISearchBar. Ширина панели поиска (200) не на весь экран. Я ищу как MSWord и отображаю содержимое в табличном представлении панели поиска. Но когда пользователь находится в середине поиска и изменил ориентацию, как мне контролировать ширину панели поиска, т. Е. self.searchDisplayController.searchBar.frame и self.searchDisplayController.searchResultsTableView.frame.

Ниже приведен фрагмент кода, который использовался для создания панели поиска:

-(IBAction)searchBar:(id)sender
{
    if(!searching)
    {
        searching = YES;
        sBar.frame = CGRectMake(500, 50,250, 44);
        [self.view addSubview:sBar];
        [searchController setActive:YES animated:YES];
        [sBar becomeFirstResponder];

        if((currentOrientation == UIInterfaceOrientationLandscapeLeft)  || 
           (currentOrientation ==  UIInterfaceOrientationLandscapeRight))
        {
            self.searchDisplayController.searchBar.frame = CGRectMake(755, 50, 250, 44);
        }
        else 
        {
            self.searchDisplayController.searchBar.frame = CGRectMake(500, 50, 250, 44);
        }
    }
}


- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
    [self filterContentForSearchText:searchString scope:
     [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];

    // Return YES to cause the search result table view to be reloaded.
    return YES;
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
     [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];

    // Return YES to cause the search result table view to be reloaded.
    return YES;
}

- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller{
    /*
     Bob: Because the searchResultsTableView will be released and allocated automatically, so each time we start to begin search, we set its delegate here.
     */
    [self.searchDisplayController.searchResultsTableView setDelegate:self];
    [self.searchDisplayController.searchResultsTableView setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:204/255.0 alpha:1.0]];
}

- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller{
    /*
     Hide the search bar
     */

    float animateTime = 0.3;
    CGRect viewFrame = sBar.frame;
    viewFrame.origin.y -= (viewFrame.size.height);

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animateTime];

    sBar.frame = viewFrame;

    [UIView commitAnimations];
    [self performSelector:@selector(animationDone) withObject:nil afterDelay:0.3];

}

-(void)animationDone
{
    [sBar removeFromSuperview];
    searching = NO;
}


-(void)searchDisplayController:(UISearchDisplayController *)controller didShowSearchResultsTableView:(UITableView *)tableView 
{
    if((currentOrientation == UIInterfaceOrientationLandscapeLeft)  || 
       (currentOrientation ==  UIInterfaceOrientationLandscapeRight))
    {
        tableView.frame = CGRectMake(755, 100, 250, 400);
    }
    else 
    {
        tableView.frame = CGRectMake(500, 100, 250, 400);
    }
}



- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation 
                                duration:(NSTimeInterval)duration
{
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    currentOrientation = toInterfaceOrientation;



    if((currentOrientation == UIInterfaceOrientationLandscapeLeft)  || 
       (currentOrientation ==  UIInterfaceOrientationLandscapeRight))
    {

        //Search
        btnSearch.frame = CGRectMake(920, 5, 40, 40);

        self.searchDisplayController.searchBar.frame = CGRectMake(755, 50, 250, 44);
        self.searchDisplayController.searchResultsTableView.frame = CGRectMake(755, 100, 250, 400);
    }
    else 
    {

        //Search
        btnSearch.frame = CGRectMake(666, 5, 40, 40);

        self.searchDisplayController.searchBar.frame = CGRectMake(500, 50, 250, 44);
        self.searchDisplayController.searchResultsTableView.frame = CGRectMake(500, 100, 250, 400);
    }
}

Я могу создать и функциональность, которая работает нормально. Но единственная проблема заключается в том, что когда пользователь меняет ориентацию, он неправильно устанавливает ширину панели поиска. Моя заявка должна быть доставлена ​​в эту пятницу. Пожалуйста, ответьте мне как можно скорее.


person Srivathsa    schedule 27.09.2012    source источник


Ответы (1)


Отвечая на мой вопрос, чтобы закрыть эту тему, а также помочь другим.

(1) В willRotateToInterfaceOrientation можно установить происхождение UISearchBar. Ширина составляет 768 (полная ширина экрана iPad в портретной ориентации), но, похоже, здесь установлено происхождение.

(2) После завершения изменения ориентации мы можем установить ширину панели поиска. При небольшой анимации размер будет плавным.

(3) Я вызываю resetFrame как в API-интерфейсах до, так и после ориентации, чтобы избежать внезапного вида JURK для searchBar.

Ниже приведено решение, которое я использовал для своего приложения.

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation 
                                duration:(NSTimeInterval)duration
{
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    currentOrientation = toInterfaceOrientation;



    [self resetSearchResourcesFrames];  // Set the origin of UISearchBar
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
    [UIView beginAnimations:@"" context:nil]; //Animation for smooth resizing of search tableview only
    [UIView setAnimationDuration:0.2];
    [self resetSearchResourcesFrames];  // Width rotation only possible after rotation
    [UIView commitAnimations];
}

-(void)resetSearchResourcesFrames
{
    if(([buttonGridViewController sharedInstance].currentOrientation == UIInterfaceOrientationLandscapeLeft)  || 
       ([buttonGridViewController sharedInstance].currentOrientation ==  UIInterfaceOrientationLandscapeRight))
    {
        //Search
        btnSearch.frame = CGRectMake(920, 5, 40, 40);

        self.searchDisplayController.searchBar.frame = CGRectMake(755, 50, 250, 44);
        self.searchController.searchResultsTableView.frame = CGRectMake(755, 100, 250, 400);
    }
    else 
    {
        //Search
        btnSearch.frame = CGRectMake(666, 5, 40, 40);

        self.searchDisplayController.searchBar.frame = CGRectMake(500, 50, 250, 44);
        self.searchController.searchResultsTableView.frame = CGRectMake(500, 100, 250, 400);
    }
}
person Srivathsa    schedule 03.10.2012