안녕하세요. iOSangBong입니다.
오늘은 모달이나 fullScreenCover를 사용했을때 배경을 투명하게 만들어보겠습니다.
지난 시간엔 fullScreenCover에서 애니메이션을 없애보았는데
사용했던 프로젝트를 가져오겠습니다.
지난 시간엔 띄워진 배경의 색이 Orange색이 여서 QR코드가 잘 안보였었습니다.
여기서 단순히 background(Color.clear)를 하게 되면
이렇게 배경이 그냥 투명색으로 보이고 iOSangBong만 보이게 됩니다.
하지만 저는 QR코드 화면이 보고 싶습니다.
그러나 공식적으로 지원하는 기능은 없는 걸로 알고 있습니다.
새로 만들어보죠!
UIView Representable을 이용해서 ClearBackground를 만들어주고
비교를 위해 기존의 배경색에 opacity를 주고 글씨를 조금 내려서
적용을 해보면~?
... 쨘~
원하는 대로 뒤의 QR코드가 제대로 보이고 있습니다...
그러나 여기서 추가적으로 문제가 발생하게 되는데
iOS16에서 배경색이 설정되는데 때때로 지연이 발생해 View가 나타날때 깜빡이는 현상이 발생합니다..
이를 해결하기 위해...
ClearBackgroundView를 선언해서 layoutSubviews에서
background를 clear 시켜주고
ClearBackground에 UIView 대신 ClearBackgroundView를 선언을 해줍니다.
그러면 정상적으로 작동을 하실겁니다 후후..
이 기능으로 커스텀 UI를 만드는데 유용하게 쓸 수 있는데요...
다음 포스팅은 커스텀 UI를 올려보도록 하겠습니다!
참고를 위해 코드를 올려놓겠습니다.
struct ContentView: View {
@State private var isPresented: Bool = false
var body: some View {
VStack {
Image(uiImage: BongQRCode.generateQRCode())
.onTapGesture {
self.isPresented.toggle()
}
}
.fullScreenCover(isPresented: $isPresented) {
ModalView(isPresented: $isPresented)
}
}
struct ModalView: View {
@Binding var isPresented: Bool
var body: some View {
VStack {
Text("iOSangBong")
.offset(y:200)
.onTapGesture {
self.isPresented.toggle()
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.orange.opacity(0.3)) // 화면 표시용
.background(ClearBackground())
}
}
struct ClearBackground: UIViewRepresentable {
public func makeUIView(context: Context) -> UIView {
let view = ClearBackgroundView()
DispatchQueue.main.async {
view.superview?.superview?.backgroundColor = .clear
}
return view
}
public func updateUIView(_ uiView: UIView, context: Context) {}
}
class ClearBackgroundView: UIView {
open override func layoutSubviews() {
guard let parentView = superview?.superview else {
return
}
parentView.backgroundColor = .clear
}
}
다들 즐코딩 하세요. 그럼 이만~
'SwiftUI > 2. 잡기술' 카테고리의 다른 글
[iOS][SwiftUI] 키보드 간단하게 내리기 (0) | 2023.08.21 |
---|---|
[iOS][SwiftUI] Rectangle 특정 모서리 둥글게 만들기 (0) | 2023.08.07 |
[iOS][SwiftUI] @focusState를 Binding 하기 (0) | 2023.08.02 |
[iOS][SwiftUI] safeArea 길이 구하기 (0) | 2023.07.25 |
[iOS][SwiftUI] Modal, fullScreenCover 애니메이션 없애기 (0) | 2023.07.13 |