了解UIViewRepresentable

时间:2020-06-01 11:34:04

标签: swift swiftui uiviewrepresentable

Swift 5.0 iOS 13

试图了解UIViewRepresentable的工作原理,并在几乎所有地方都放了这个简单的示例,但也许完全是胡说八道。是的,我知道SwiftUI中已经有一个tapGesture,这只是一个测试。

不会编译,因为它说从初始化程序返回之前,并非在所有路径上都调用“ 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")
  }
 }

}

2 个答案:

答案 0 :(得分:1)

那是因为您的CoordinatorUIView的子类,而您

必须调用超类'UIView'的指定初始化程序

init返回之前:

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

答案 1 :(得分:1)

只要使您的CoordinatorNSObject,它通常就扮演着桥梁/控制器/代表/演员的角色,但没有表现力,因此不应is-a-UIView

final class Coordinator: NSObject {
  private let view: UIView

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

还有一个...

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
}