iOS SwiftUI) WebView 띄우기
ContentView (SwiftUI) -> MyWebView (UIViewRepresentable) 띄우기
첫화면 (ContentView.swift)
// ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
HStack {
NavigationLink(destination:
MyWebView(urlToLoad: "https://www.naver.com")
.edgesIgnoringSafeArea(.all)
) {
Text("네이버")
.font(.system(size:20))
.fontWeight(.bold)
.padding(20)
.background(Color.green)
.foregroundColor(Color.white)
.cornerRadius(20)
}
NavigationLink(destination:
MyWebView(urlToLoad: "https://www.daum.net")
.edgesIgnoringSafeArea(.all)
) {
Text("다음")
.font(.system(size:20))
.fontWeight(.bold)
.padding(20)
.background(Color.orange)
.foregroundColor(Color.white)
.cornerRadius(20)
}
NavigationLink(destination:
MyWebView(urlToLoad: "https://www.google.com")
.edgesIgnoringSafeArea(.all)
) {
Text("구글")
.font(.system(size:20))
.fontWeight(.bold)
.padding(20)
.background(Color.blue)
.foregroundColor(Color.white)
.cornerRadius(20)
}
}
}
}
}
WebView를 띄울 때는 UIKit의 UIView 즉 UIViewRepresentable을 띄운다고 생각하면 됨
핵심 메서드 2개
1. makeUIView
2. updateUIView
// MyWebView.swift
import SwiftUI
import WebKit
//UIKit의 UIView를 사용할 수 있도록 한다.
//UIViewControllerRepresentable
struct MyWebView: UIViewRepresentable {
var urlToLoad: String
//UIView 만들기
func makeUIView(context: Context) -> WKWebView {
guard let url = URL(string: self.urlToLoad) else {
return WKWebView()
}
//웹뷰 인스턴스 생성
let webview = WKWebView()
//웹뷰를 로드한다.
webview.load(URLRequest(url: url))
return webview
}
//업데이트 UI View
func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContext<MyWebView>) {
}
}
참고)
SwiftUI 프로젝트 생성시, ~~App.swift (App으로 끝나는 파일이 AppDelegate, SceneDelegate 역할한다고 생각하면 됨
// SwiftUI_WebViewApp.swift
import SwiftUI
@main
struct SwiftUI_WebViewApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
ContentView()로부터 앱이 시작한다고 생각하면 되는거
참고) https://www.youtube.com/watch?v=kalSK-3PPnc&list=PLgOlaPUIbynqyJHiTEv7CFaXd8g5jtogT&index=4
'iOS > SwiftUI' 카테고리의 다른 글
SwiftUI에서 Info.plist 사용 방법 (0) | 2023.10.01 |
---|---|
iOS SwiftUI) List (UIKit의 tableView에 해당) (0) | 2023.02.22 |
iOS SwiftUI) Image (0) | 2023.02.20 |
iOS SwiftUI) Text 관련 (0) | 2023.02.20 |
SwiftUI 기본 정리 (0) | 2023.02.20 |