SwiftUI에서 UIkit 사용하기


SwiftUI에서 UIkit를 사용하기 위해서는 UIViewRepresentable을 채택하는 struct를 구현하면 됩니다.

UIViewRepresentable을 채택하게 되면 필수로 구현해야 하는 makeUIView와 updateUIView가 있고 UIViewType을 원하는 UIkit의 View로 변경하면 됩니다.

UIViewRepresentable

// 구현
struct SwiftUIView: UIViewRepresentable {
	func makeUIView(context: Context) -> UIViewType {
    	let view = UIViewType()
        return view
    }
    
    func updateUIView(_ view: UIViewType, context: Context) {
    
    }
}


// 사용
struct MyView: View {
	var body: some View {
    	VStack { 
        	SwiftUIView()
        }
    }
}

UIViewControllerRepresentable

만약 Custom View가 아닌 하나의 Controller일때는 UIViewControllerRepresentable이라는 것을 따로 제공합니다. 

makeUIViewController에 해당하는 ViewController를 리턴하도록 해주면 됩니다.

struct MyViewControllerRepresentation: UIViewControllerRepresentable { 
	func makeUIViewController(context: Context) -> ViewController {
		
    }

	func updateUIViewController(_ uiViewController: ViewController, context: Context) { 
    
    } 
}

 

 

SwiftUI에서 Storyboard 사용하기


코드로 구현된 UIViewController가 아닌 Storyboard(.xib)로 구현되어있다면 어떻게 해야할까요?

UIStoryboard

struct MyViewControllerRepresentation: UIViewControllerRepresentable { 
	func makeUIViewController(context: Context) -> ViewController {
		UIStoryboard(name: "MyStoryBoardView", bundle: nil)
        	.instantiateViewController(withIdentifier: "ViewController") as! ViewController
    }

	func updateUIViewController(_ uiViewController: ViewController, context: Context) { 
    
    } 
}



반응형

+ Recent posts