简体   繁体   English

了解 UIViewRepresentable

[英]Understanding UIViewRepresentable

Swift 5.0 iOS 13 Swift 5.0 iOS 13

Trying to understand how UIViewRepresentable works, and put together this simple example, almost there, but maybe its complete nonsense.试图理解 UIViewRepresentable 是如何工作的,并把这个简单的例子放在一起,几乎就在那里,但也许它完全是胡说八道。 Yes, I know there is already a tapGesture in SwiftUI, this is just a test.是的,我知道 SwiftUI 中已经有一个 tapGesture,这只是一个测试。

Won't compile cause it says 'super.init' isn't called on all paths before returning from initialiser, which I try and set but obviously not correctly.不会编译,因为它说在从初始化程序返回之前没有在所有路径上调用“super.init”,我尝试设置但显然不正确。

import SwiftUI

struct newView: UIViewRepresentable {

typealias UIViewType = UIView
var v = UIView()

func updateUIView(_ uiView: UIView, context: Context) {
  v.backgroundColor = UIColor.yellow
}


func makeUIView(context: Context) -> UIView {
  let tapGesture = UITapGestureRecognizer(target: self, action: #selector(Coordinator.handleTap(sender:)))
  v.addGestureRecognizer(tapGesture)
  return v
}

func makeCoordinator() -> newView.Coordinator {
  Coordinator(v)
}

final class Coordinator: UIView {
  private let view: UIView

init(_ view: UIView) {
    self.view = view
}

required init?(coder: NSCoder) {
  fatalError("init(coder:) has not been implemented")
}

@objc func handleTap(sender: UITapGestureRecognizer) {
    print("tap")
  }
 }

}

Just make your Coordinator is a NSObject , it usually plays bridge/controller/delegate/actor role, but not presentation, so should not be is-a-UIView只是让你的Coordinator是一个NSObject ,它通常扮演桥梁/控制器/代表/演员角色,但不是演示,所以不应该是is-a-UIView

final class Coordinator: NSObject {
  private let view: UIView

init(_ view: UIView) {
    self.view = view
}

and one more...还有一个……

func makeUIView(context: Context) -> UIView {
  // make target a coordinator, which is already present in context !!
  let tapGesture = UITapGestureRecognizer(target: context.coordinator, 
        action: #selector(Coordinator.handleTap(sender:)))
  v.addGestureRecognizer(tapGesture)
  return v
}

Thats because your Coordinator is a subclass of the UIView and you那是因为您的CoordinatorUIView的子类,而您

Must call a designated initializer of the superclass 'UIView'必须调用超类“UIView”的指定初始化程序

before returning from the init :在从init返回之前:

init(_ view: UIView) {
    self.view = view
    super.init(frame: .zero) // Or any other frame you need
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM