Skip to content

Instantly share code, notes, and snippets.

@TuenTuenna
Last active March 24, 2022 02:32
Show Gist options
  • Save TuenTuenna/ad16f07645e59ef8e115fda8e0511031 to your computer and use it in GitHub Desktop.
Save TuenTuenna/ad16f07645e59ef8e115fda8e0511031 to your computer and use it in GitHub Desktop.
SwiftUi - TabView 기본 탭바 숨기기 및 높이 변경

UITabBarController 에 탭바를 가져오기 위한 TabBarAccessor

// Helper bridge to UIViewController to access enclosing UITabBarController
// and thus its UITabBar
struct TabBarAccessor: UIViewControllerRepresentable {
    var callback: (UITabBar) -> Void
    private let proxyController = ViewController()

    func makeUIViewController(context: UIViewControllerRepresentableContext<TabBarAccessor>) ->
                              UIViewController {
        proxyController.callback = callback
        return proxyController
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<TabBarAccessor>) {
    }

    typealias UIViewControllerType = UIViewController

    // viewWillAppear 가 탈때 가지고 있는 탭바를 클로저 콜백으로 넘겨준다.
    private class ViewController: UIViewController {
        var callback: (UITabBar) -> Void = { _ in }

        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            if let tabBar = self.tabBarController {
                self.callback(tabBar.tabBar)
            }
        }
    }
}

익스텐션으로 간편하게 쓰도록 만들기

extension View {
    
    /// 탭바 숨김 처리 여부
    /// - Parameter isHidden:
    /// - Returns: 
    func setTabBarVisibility(isHidden : Bool) -> some View {
      background(TabBarAccessor { tabBar in
          print(">> TabBar height: \(tabBar.bounds.height)")
          // !! use as needed, in calculations, @State, etc.
          // 혹은 높이를 변경한다던지 여러가지 설정들이 가능하다. 
          tabBar.isHidden = isHidden
      })
  }
}

사용 예

// Demo SwiftUI view of usage
struct TestTabBar: View {
    var body: some View {
        TabView {
            Text("First View")
                .setTabBarVisibility(isHidden: true)
                .tabItem { Image(systemName: "1.circle") }
                .tag(0)
            Text("Second View")
                .tabItem { Image(systemName: "2.circle") }
                .tag(1)
        }
    }
}

출처

https://stackoverflow.com/questions/59969911/programmatically-detect-tab-bar-or-tabview-height-in-swiftui/59972635#59972635

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment