使内容模式适合SwiftUI中的自定义视图

时间:2020-02-19 21:03:07

标签: swift swiftui

如何将内容模式设置为适合SwiftU中包装的自定义UIImageView

struct CustomView: UIViewRepresentable {
    func makeUIView(context: Context) -> UIImageView {
        CustomUIImage()
    }

    func updateUIView(_ uiView: UIImageView, context: Context) {
    }
}

struct ContentView: View {
    var body: some View {
        CustomView()
    }
}

在上面的代码中,CustomUIImageUIImageView的{​​{1}}的子类。它包装在UIKit中,以将其与SwiftUI框架集成。在这种情况下,致电UIViewRepresentable无效

1 个答案:

答案 0 :(得分:1)

这是可行的方法

struct CustomView: UIViewRepresentable {

    private let imageView = CustomUIImage()

    init(contentMode: UIView.ContentMode = .center) {
        imageView.contentMode = contentMode
    }

    func makeUIView(context: Context) -> UIImageView {
        imageView
    }

    func updateUIView(_ uiView: UIImageView, context: Context) {
    }
}

struct ContentView: View {
    var body: some View {
        CustomView(contentMode: .scaleAspectFit)
    }
}