Nice programing

uitabbarcontroller를 숨기는 방법

nicepro 2020. 10. 17. 12:25
반응형

uitabbarcontroller를 숨기는 방법


에 문제가 UITabBarController있습니다. 내 응용 프로그램에서 나는 그것을 숨기고 싶지만 hidesBottomBarWhenPushed밀 때가 아니라 숨기고 싶기 때문에 사용 하지 않습니다. 예를 들어 애플리케이션에서 숨기기 버튼을 누를 때이를 숨기고 싶습니다.

Google에서 많은 기사를 읽었지만 어떻게 할 수 있는지 알 수 없습니다.


내 작업 코드에서 붙여넣고 있습니다 ...이 메서드를 호출하여 tabbarcontroller를 숨기고 표시 할 수 있습니다 .... tabbarcontroller 인스턴스를 이러한 함수에 전달하기 만하면됩니다.

// Method call
[self hideTabBar:self.tabBarController];   

// Method implementations
- (void)hideTabBar:(UITabBarController *) tabbarcontroller
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];

    for(UIView *view in tabbarcontroller.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, 480, view.frame.size.width, view.frame.size.height)];
        } 
        else 
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, 480)];
        }
    }

    [UIView commitAnimations];   
}

- (void)showTabBar:(UITabBarController *) tabbarcontroller
{       
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    for(UIView *view in tabbarcontroller.view.subviews)
    {
        NSLog(@"%@", view);

        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, 431, view.frame.size.width, view.frame.size.height)];

        } 
        else 
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, 431)];
        }
    }

    [UIView commitAnimations]; 
}

가로, 세로 및 iPad 모두에서 작동하도록 Setomidor의 답변을 수정했습니다 (320 및 480 값은 iPhone에서만 작동 함).

- (void) hideTabBar:(UITabBarController *) tabbarcontroller 
{
    CGRect screenRect = [[UIScreen mainScreen] bounds];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    float fHeight = screenRect.size.height;
    if(  UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation) )
    {
        fHeight = screenRect.size.width;
    }

    for(UIView *view in tabbarcontroller.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
        } 
        else 
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, fHeight)];
            view.backgroundColor = [UIColor blackColor];
        }
    }
    [UIView commitAnimations];
}



- (void) showTabBar:(UITabBarController *) tabbarcontroller 
{   
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    float fHeight = screenRect.size.height - tabbarcontroller.tabBar.frame.size.height;

    if(  UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation) )
    {
        fHeight = screenRect.size.width - tabbarcontroller.tabBar.frame.size.height;
    }

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];
    for(UIView *view in tabbarcontroller.view.subviews)
    {   
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];            
        } 
        else 
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, fHeight)];
        }       
    }
    [UIView commitAnimations]; 
}

또한 UIDevice 방향 변경으로 iOS 6에 도입 된 변경 사항을 처리하고 장치가 누워있을 때도 제대로 작동하도록 코드를 수정했습니다.


버튼에 대한 작업 방법 :

[self.tabBarController.tabBar setHidden:YES];

Saurahb 및 karlbecker_com의 솔루션은 뷰가 포함되어있는 경우가 명백한 터지는 효과를 일으킬 수 있지만, 중대하다 있는 tableview를 탭 표시 줄의 애니메이션 백업있다. 나는 약간의 수정을하고 그것을 단일 함수로 결합했다 (UITabBarController의 카테고리로). 완전히 완벽하지는 않지만 (지연된 보정 애니메이션) 테이블에서 좋은 결과를 제공합니다.

애니메이션 블록과 카테고리가 마음에 드시면 시도해보세요. 방향 및 장치 친화적입니다.

UITabBarController + ShowHideBar.m :

#import "UITabBarController+ShowHideBar.h"

@implementation UITabBarController (ShowHideBar)

- (void) setHidden:(BOOL)hidden{

    CGRect screenRect = [[UIScreen mainScreen] bounds];
    float fHeight = screenRect.size.height;
    if(  UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation) ){
        fHeight = screenRect.size.width;
    }

    if(!hidden) fHeight -= self.tabBar.frame.size.height;

    [UIView animateWithDuration:0.25 animations:^{
        for(UIView *view in self.view.subviews){
            if([view isKindOfClass:[UITabBar class]]){
                [view setFrame:CGRectMake(view.frame.origin.x, fHeight, view.frame.size.width, view.frame.size.height)];
            }else{
                if(hidden) [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, fHeight)];
            }
        }
    }completion:^(BOOL finished){
        if(!hidden){

            [UIView animateWithDuration:0.25 animations:^{

                for(UIView *view in self.view.subviews)
                {
                    if(![view isKindOfClass:[UITabBar class]])
                        [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, fHeight)];
                }

            }];
        }
    }];

}

@end

UITabBarController + ShowHideBar.h :

#import <UIKit/UIKit.h>

@interface UITabBarController (ShowHideBar)

- (void) setHidden:(BOOL)hidden;

@end

용법:

[self.tabBarController setHidden:YES];
[self.tabBarController setHidden:NO];

위의 Saurabh의 답변은 가로 방향으로도 작동하도록 확장 할 수 있습니다.

+ (void) hideTabBar:(UITabBarController *) tabbarcontroller {

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

    //Support for landscape views
    int orientation = [[UIDevice currentDevice] orientation];
    int x_pos = 480;
    if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
        x_pos = 320;
    }

    for(UIView *view in tabbarcontroller.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, x_pos, view.frame.size.width, view.frame.size.height)];
        } 
        else 
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, x_pos)];
        }       
    }   
    [UIView commitAnimations]; 
}

`

showTabBar ()에 해당하는 x_pos 번호는 431271입니다.


@karlbecker_com Answer는 iPhone 4와 iPhone 5 모두에서 완벽하게 작동합니다. 하단의 iOS7 검은 색 막대에 문제가있는 사람이 있으면 tabBarController를 반투명으로 설정합니다.

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

// To Hide the black line in IOS7 only, this extra bit is required
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
    [self.tabBarController.tabBar setTranslucent:YES];
}  

이것은 MonoTouch (Xamarin.iOS)로 포팅 된 karlbecker_com의 답변입니다. 유일한 차이점은 UITabBarController에서 상속 된 클래스에 메서드를 구현했기 때문에 " tabbarcontroller"에 대한 참조가 " "로 대체되었다는 것 this입니다.

public void HideTabBar()
{
    var screenRect = UIScreen.MainScreen.Bounds;
    float fHeight = screenRect.Height;
    if(UIApplication.SharedApplication.StatusBarOrientation == UIInterfaceOrientation.LandscapeLeft
       || UIApplication.SharedApplication.StatusBarOrientation == UIInterfaceOrientation.LandscapeRight)
    {
        fHeight = screenRect.Width;
    }

    UIView.BeginAnimations(null);
    UIView.SetAnimationDuration(0.4);
    foreach(UIView view in this.View.Subviews)
    {
        if(view is UITabBar)
        {
            view.Frame = new RectangleF(view.Frame.X, fHeight, view.Frame.Width, view.Frame.Height);
        } 
        else 
        {
            view.Frame = new RectangleF(view.Frame.X, view.Frame.Y, view.Frame.Width, fHeight);
            view.BackgroundColor = UIColor.Black;
        }
    }
    UIView.CommitAnimations();
}

public void ShowTabBar()
{   
    var screenRect = UIScreen.MainScreen.Bounds;
    float fHeight = screenRect.Height - 49f;
    if(UIApplication.SharedApplication.StatusBarOrientation == UIInterfaceOrientation.LandscapeLeft
       || UIApplication.SharedApplication.StatusBarOrientation == UIInterfaceOrientation.LandscapeRight)
    {
        fHeight = screenRect.Width - 49f;
    }

    UIView.BeginAnimations(null);
    UIView.SetAnimationDuration(0.4);
    foreach(UIView view in this.View.Subviews)
    {
        if(view is UITabBar)
        {
            view.Frame = new RectangleF(view.Frame.X, fHeight, view.Frame.Width, view.Frame.Height);
        } 
        else 
        {
            view.Frame = new RectangleF(view.Frame.X, view.Frame.Y, view.Frame.Width, fHeight);
        }
    }
    UIView.CommitAnimations();
}

IOS 7.1부터 "Swift" 솔루션 :

self.tabBarController?.tabBar.hidden = true // hide tabbar
self.tabBarController?.tabBar.hidden = false // show tabbar

이것이 도움이되기를 바랍니다!


모달 뷰 컨트롤러를 푸시 할 수 있습니다.

[self presentModalViewController:myFullscreenViewController animated:YES];

이렇게하면 현재보기 위에 완전히 새로운보기 전체 화면이 생성됩니다.

함께 해산하다 dismissModalViewController:animated:


아래 솔루션은 TabBar 애니메이션을 사용하여 전체 화면 모드로 이동해야하는 경우와 똑같은 사용 사례에서 잘 작동합니다.

기본적으로 아이디어는

  1. UITabBar 의 스냅 샷 만들기 ;

  2. UITabBar 와 동일한 프레임을 가진 UIImageView에 스냅 샷 UIImage추가합니다 .

  3. 기본 뷰의 크기를 조정하고 self.tabBarController.view에 배치합니다 .

  4. 세트 의 UITabBar 의 알파 0.0하는 단계;

  5. self.tabBarController.viewUITabBar 의 스냅 샷이 있는 UIImageView배치합니다 .

  6. 위의 내용이 달성되면 모든 종류의 애니메이션을 수행하십시오.

    #import "QuartzCore/CALayer.h"
    
    @implementation FTBFirstViewController {
       BOOL hidden;
       UIImageView *fakeTabBarImageView;
       UIView *viewToResize;
    }
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        //////////////////////////////
        // Create your viewToResize
        //////////////////////////////
        [self.view addSubview:viewToResize];
    
        hidden = NO;
    }
    
    - (void)hideTabBar:(id)sender {
        if (!hidden) {
            //
            // to create the fake UITabBar
            fakeTabBarImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
            UIImage *fakeTabBarImage = [self imageScreenshotFromView:self.tabBarController.tabBar];
            fakeTabBarImageView.image = fakeTabBarImage;
            fakeTabBarImageView.frame = self.tabBarController.tabBar.frame;
            //
            // to resize underlying UIView
            viewToResize.frame = (CGRect){viewToResize.frame.origin.x, viewToResize.frame.origin.y + 20.f, viewToResize.frame.size.width, viewToResize.frame.size.height + fakeTabBarImageView.frame.size.height};
            //
            // to hide real UITabBar
            self.tabBarController.tabBar.alpha = 0.0;
            //
            // to add views in exactly this order
            [self.tabBarController.view addSubview:viewToResize];
            [self.tabBarController.view addSubview:fakeTabBarImageView];
            //
            // do any sort of animation
            [UIView animateWithDuration:0.8 animations:^{
                fakeTabBarImageView.frame = (CGRect){fakeTabBarImageView.frame.origin.x, fakeTabBarImageView.frame.origin.y + fakeTabBarImageView.frame.size.height, fakeTabBarImageView.frame.size};
            }];
    
            hidden = YES;
        } else {
            [UIView animateWithDuration:0.8 animations:^{
                    fakeTabBarImageView.frame = (CGRect){fakeTabBarImageView.frame.origin.x, fakeTabBarImageView.frame.origin.y - fakeTabBarImageView.frame.size.height, fakeTabBarImageView.frame.size};
            } completion:^(BOOL complete){
                self.tabBarController.tabBar.alpha = 1.0;
                [fakeTabBarImageView removeFromSuperview];
                fakeTabBarImageView = nil;
    
                viewToResize.frame = self.view.frame;
                [self.view addSubview:viewToResize];
    
                [fakeTabBarImageView removeFromSuperview];
            }]; 
    
            hidden = NO;
        }
    }
    
    - (UIImage *)imageScreenshotFromView:(UIView *)aView {
        UIImage *viewImage;
    
        UIGraphicsBeginImageContextWithOptions(aView.bounds.size, aView.opaque, [[UIScreen mainScreen] scale]);
        [aView.layer renderInContext:UIGraphicsGetCurrentContext()];
        viewImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return viewImage;
    }
    

나는이 모든 답변을 거의 시도했지만 그중 어느 것도 나를 위해 일하지 않았습니다. 내 앱에는 루트 뷰로 UITabBarController가 있고 각 탭에는 UINavigationController가 있습니다. UINavigationController 중 하나에는 상위 뷰 컨트롤러로 UICollectionViewController가 있습니다. 사용자가 UICollectionView에서 항목을 선택할 때 세부 정보보기 컨트롤러가 탐색 스택으로 푸시되기를 원했습니다. 내 상세보기에는 하단에 도구 모음이 있습니다. 도구 모음이 어리석은 것처럼 보이기 때문에 탭 막대 위에 표시되는 것을 원하지 않았으며이보기에서 탭 컨텍스트를 전환 할 필요가 없습니다. UIToolbars 및 UITabBars를 수동으로 배치하고 UITabBarController 및 내장 UIToolbar를 사용하지 않음으로써이 문제를 쉽게 해결할 수 있었지만 리팩토링이 너무 많고 다소 우아하지 않은 것처럼 보였습니다.

결국 내 솔루션은 매우 간단했습니다. UITabBarController의 경계를 화면 하단에서 확장했습니다. 내 디테일 뷰 컨트롤러에 이것을 추가했습니다.

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    // Extend the UITabBarController to shift the tab bar off screen
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGRect tabBarControllerFrame = self.tabBarController.view.frame;
    if (animated) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.5];
        tabBarControllerFrame.size.height = screenRect.size.height +
            self.tabBarController.tabBar.frame.size.height;
        [self.tabBarController.view setFrame:tabBarControllerFrame];
        [UIView commitAnimations];
    }
    else {
        tabBarControllerFrame.size.height = screenRect.size.height +
            self.tabBarController.tabBar.frame.size.height;
        [self.tabBarController.view setFrame:tabBarControllerFrame];
    }

    // Now show the toolbar
    [self.navigationController setToolbarHidden:NO animated:animated];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

    // Ensure the UITabBarController remains extended when subviews are laid out
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGRect tabBarControllerFrame = self.tabBarController.view.frame;
    tabBarControllerFrame.size.height = screenRect.size.height + 
        self.tabBarController.tabBar.frame.size.height;
    [self.tabBarController.view setFrame:tabBarControllerFrame];
}

그런 다음 사용자가 UINavigationController의 맨 위로 돌아올 때 탭 표시 줄을 다시 표시하기 위해이를 상위 뷰 컨트롤러에 추가했습니다.

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    // Hide toolbar
    [self.navigationController setToolbarHidden:YES animated:animated];

    // Tab bar back on to screen
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGRect tabBarControllerFrame = self.tabBarController.view.frame;
    if (tabBarControllerFrame.size.height != screenRect.size.height) {
        if (animated) {
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.5];
            tabBarControllerFrame.size.height = screenRect.size.height;
            [self.tabBarController.view setFrame:tabBarControllerFrame];
            [UIView commitAnimations];
        }
        else {
            tabBarControllerFrame.size.height = screenRect.size.height;
            [self.tabBarController.view setFrame:tabBarControllerFrame];
        }
    }
}

iOS8 에서는 Swift hidden에서 tabBar
Like 속성 만 설정하면 됩니다.

rootTabVC = UITabBarController()
rootTabVC?.tabBar.hidden = true

나는이 작업을 수행 didFinishLaunchingWithOptionsappdelegate그리고 내가 당신은 또한 설정하는 데 필요한 이전의 iOS 버전에서 제대로 기억한다면 내 생각, 잘 작동 frametabBar그렇지 않으면이 화면 밖으로 뭔가를 tabbar보여주지 것입니다하지만 여전히 공간을 차지합니다.


@Saurabh 코드의 스위프트 및 수정 버전

방법

func setTabBarHidden (bool:Bool){
        for view in tabBarController!.view.subviews {
            if (view.isKindOfClass(UITabBar)){
                let tabBar = view as! UITabBar
                UIView.animateWithDuration(0.3, animations: { () -> Void in
                    var offset = CGFloat(50)
                    if (bool == false){
                        offset = -50;
                    }
                    tabBar.frame = CGRect(origin: CGPointMake(tabBar.frame.origin.x, tabBar.frame.origin.y + offset), size: tabBar.frame.size)
             })   
        }
    }
}

보여주기 위해

override func viewDidLoad() {
     setTabBarHidden(true)
}

숨기려고

override func viewWillDisappear(animated: Bool) {
    setTabBarHidden(false)
}

다음은 테이블이없는 VC를위한 @Thomas Verbeek 버전의 얇고 빠른 포트입니다 (iOS 8.4에서 테스트 됨).

extension UITabBarController {

    /**
    Shows or hides the tabbar

    :param: hidden            whether to show or hide the tabbar
    :param: animationDuration the animation's duration
    */
    func setHidden(hidden:Bool, animationDuration:NSTimeInterval = 0.25) {

        let screenRect = UIScreen.mainScreen().bounds
        var fHeight = screenRect.size.height

        if !hidden {
            fHeight -= self.tabBar.frame.size.height
        }

        UIView.animateWithDuration(animationDuration, animations: {
                for view in self.view.subviews as! [UIView] {
                    if view is UITabBar {
                        view.frame = CGRectMake(
                            view.frame.origin.x,
                            fHeight,
                            view.frame.size.width,
                            view.frame.size.height)
                    }
                }
            })
    }
}

그리고 여기에 더 직접적인 포트 (테스트되지 않음) :

extension UITabBarController {

    /**
    Shows or hides the tabbar

    :param: hidden            whether to show or hide the tabbar
    :param: animationDuration the animation's duration
    */
    func setHidden(hidden:Bool, animationDuration:NSTimeInterval = 0.25) {

        let screenRect = UIScreen.mainScreen().bounds
        var fHeight = screenRect.size.height

        if UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) {
            fHeight = screenRect.size.width
        }

        if !hidden {
            fHeight -= self.tabBar.frame.size.height
        }

        UIView.animateWithDuration(animationDuration, animations: {
                for view in self.view.subviews as! [UIView] {
                    if view is UITabBar {
                        view.frame = CGRectMake(
                            view.frame.origin.x,
                            fHeight,
                            view.frame.size.width,
                            view.frame.size.height)
                    }
                    else if hidden {
                        view.frame = CGRectMake(
                            view.frame.origin.x,
                            view.frame.origin.y,
                            view.frame.size.width,
                            fHeight)
                    }
                }
            }, completion: { finished in
                if !hidden {
                    UIView.animateWithDuration(animationDuration, animations: {
                        for view in self.view.subviews as! [UIView] {
                            if !(view is UITabBar) {
                                view.frame = CGRectMake(
                                    view.frame.origin.x,
                                    view.frame.origin.y,
                                    view.frame.size.width,
                                    fHeight)
                            }
                        }
                    })
                }
        })
    }
}

애니메이션이 포함 된 빠른 버전에서는 isHideTabBar직접 속성 설정해야합니다 .

self.isHideTabBar = !self.isHideTabBar
UIView.animate(withDuration: 0.5, animations: {
    self.tabBarController?.tabBar.frame = (self.tabBarController?.tabBar.frame.offsetBy(dx: 0, dy: self.isHideTabBar ? 100 : -100))!
 })

탭 바를 숨기는 것은 적절한 해결책이 아니며 현재보기 컨트롤러보기 높이를 조정하지 않습니다.

대신 탭 표시 줄 자체를 높이 (숨기기)로 변환하거나 ID 변환을 통해 표시로 재설정 할 수 있습니다.

extension UITabBarController {
    func setBarHiddenAnimated(_ hidden:Bool) {
        UIView.animate(withDuration: 0.3, animations: {
            if hidden {
                self.tabBar.transform = CGAffineTransform(translationX: 0, y: self.tabBar.frame.size.height)
            } else {
                self.tabBar.transform = CGAffineTransform.identity
            }
        })
    }
}

애니메이션 중에 검은 색 배경을 제거하려면 뷰 컨트롤러를 '하단 막대 아래로 확장'및 '불투명 막대 아래로 확장'으로 설정해야 할 수 있습니다.

참고 URL : https://stackoverflow.com/questions/5272290/how-to-hide-uitabbarcontroller

반응형