[SwiftUI] UIKit 화면 프리뷰(Preview)에서 띄우기
- 언어 / 스위프트 UI
- 2023. 1. 17.
SwiftUI에서 UIKit을 사용해 화면을 표현할 수 있다는 것은 스위프트 UI 개발을 하시는 분이라면 대부분 알고 계실겁니다. 이 UIView 또는 ViewController를 프리뷰(Preview)를 이용해서 띄워보겠습니다.
▼ 다음과 같이 ViewController를 하나 생성합니다. 만약 PreviewProvider 프로토콜을 구현한 preivews 반환 값이 View 타입이 아니라면 보시다시피 에러가 납니다. UIKit의 뷰 컨트롤러를 반환하기 때문입니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
view.backgroundColor = .red | |
} | |
} |

▼ 이제 Preview 를 extension해서 UIViewControllerRepresentable 프로토콜을 구현합니다. 이때 필요한 함수가 makeUIController, updateUIViewController입니다. updateUIViewController는 그냥 정의만 하고 makeUIViewController에서 조금 전에 만든 UIViewController를 반환해주겠습니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension ContentView_Previews: UIViewControllerRepresentable { | |
func makeUIViewController(context: Context) -> some UIViewController { | |
ViewController() | |
} | |
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) { } | |
} |

▼ 이제 그냥 preview에서 ContentView_Previews()만 반환해줍니다. ContentView_Previews가 UIViewControllerRepresentable을 구현하고 UIViewController를 감싼 구조가 됩니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
// ViewController() | |
ContentView_Previews() | |
.ignoresSafeArea() | |
} | |
} |
▼ 다음과 같이 UIViewController객체를 SwiftUI 프리뷰로 사용할 수 있습니다.

'언어 > 스위프트 UI' 카테고리의 다른 글
[SwiftUI] 네비게이션 바 버튼 만들기 (0) | 2023.07.10 |
---|---|
[SwiftUI] URLSession을 이용한 간단한 JSON 통신 및 데이터 파싱 (0) | 2023.03.21 |
[SwiftUI] UIViewRepresentable 프로토콜 사용법 (0) | 2022.12.16 |
[SwiftUI] ViewModifier 를 이용한 View 익스텐션 활용 (0) | 2022.11.28 |
[SwiftUI] 텍스트 필드(TextField) 정리 (0) | 2022.11.24 |