hidden()과 @ViewBuilder를 이용해서 만들 수 있다.
나 같은 경우에는 Section Header를 구성할 때 사용했다.
상위 계층에서 hidden에 대한 boolean 값을 전달받아서 뷰의 표시를 분기처리 해주었다.
같은 섹션 헤더를 이용해서 뷰를 구성하고 있는데 모두 보기 라는 버튼이 섹션에 따라서 hidden 처리를 해주고 싶었다.
방법 1. 계층 구조에서 제거하는 방법
extension View {
/// Hide or show the view based on a boolean value.
///
/// Example for visibility:
///
/// Text("Label")
/// .isHidden(true)
///
/// Example for complete removal:
///
/// Text("Label")
/// .isHidden(true, remove: true)
///
/// - Parameters:
/// - hidden: Set to `false` to show the view. Set to `true` to hide the view.
/// - remove: Boolean value indicating whether or not to remove the view.
@ViewBuilder func isHidden(_ hidden: Bool, remove: Bool = false) -> some View {
if hidden {
if !remove {
self.hidden()
}
} else {
self
}
}
}
방법 2. 투명도 조절하는 방법
func hidden(_ shouldHide: Bool) -> some View {
opacity(shouldHide ? 0 : 1)
}
import SwiftUI
struct SectionHeader: View {
var sectionTitle: String = ""
var hidden: Bool = false
var body: some View {
HStack {
Text(sectionTitle).font(.title2)
Spacer()
Button("모두 보기"){}
.font(.subheadline)
.foregroundColor(.purple)
.hidden(hidden) // ✅ 해당 부분에서 사용
}
.padding([.leading, .trailing], 15)
}
}
https://codeutility.org/swift-dynamically-hiding-view-in-swiftui-stack-overflow/