跳到主要内容

框架集成 - SwiftUI 中的 UIKit

UIViewRepresentable

代表 UIKit 视图的视图。 当你想在里面使用 UIView 时使用这个 SwiftUI。

要使任何 UIView 在 SwiftUI 中可用,请创建一个符合UIViewRepresentable

import UIKit
import SwiftUI

struct ActivityIndicator: UIViewRepresentable {
@Binding var isAnimating: Bool

func makeUIView(context: Context) -> UIActivityIndicatorView {
let v = UIActivityIndicatorView()

return v
}

func updateUIView(_ uiView: UIActivityIndicatorView, context: Context) {
if isAnimating {
uiView.startAnimating()
} else {
uiView.stopAnimating()
}
}
}

如果你想在 UIKit 数据绑定(委托、目标/动作)和 SwiftUI,使用 Coordinator。详细信息可以在 SwiftUI 教程

import SwiftUI
import UIKit

struct PageControl: UIViewRepresentable {
var numberOfPages: Int
@Binding var currentPage: Int

func makeUIView(context: Context) -> UIPageControl {
let control = UIPageControl()
control.numberOfPages = numberOfPages
control.addTarget(
context.coordinator,
action: #selector(Coordinator.updateCurrentPage(sender:)),
for: .valueChanged)

return control
}

func updateUIView(_ uiView: UIPageControl, context: Context) {
uiView.currentPage = currentPage
}

func makeCoordinator() -> Coordinator {
Coordinator(self)
}

// This is where old paradigm located
class Coordinator: NSObject {
var control: PageControl

init(_ control: PageControl) {
self.control = control
}

@objc func updateCurrentPage(sender: UIPageControl) {
control.currentPage = sender.currentPage
}
}
}

文档 - UIViewRepresentable

UIViewControllerRepresentable

代表 UIKit 视图控制器的视图。 想用的时候用这个 SwiftUI 中的 UIViewController。

要使任何 UIViewController 在 SwiftUI 中可用,请创建一个符合 UIViewControllerRepresentable。详细信息可以在 SwiftUI 教程

import SwiftUI
import UIKit

struct PageViewController: UIViewControllerRepresentable {
var controllers: [UIViewController]

func makeUIViewController(context: Context) -> UIPageViewController {
let pageViewController = UIPageViewController(
transitionStyle: .scroll,
navigationOrientation: .horizontal)

return pageViewController
}

func updateUIViewController(_ pageViewController: UIPageViewController, context: Context) {
pageViewController.setViewControllers(
[controllers[0]], direction: .forward, animated: true)
}
}

文档 - UIViewControllerRepresentable