gpt4 book ai didi

ios - 可以从托管的 SwiftUI View 调用 UIKit UIViewController 中的闭包吗?

转载 作者:行者123 更新时间:2023-12-04 08:40:00 27 4
gpt4 key购买 nike

我在主持 ContentViewWrapperViewController像这样:

class WrapperViewController: UIViewController {

init() {
super.init(nibName: nil, bundle: nil)
}

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

override func loadView() {

self.view = UIView()

var contentView = ContentView()
contentView.buttonTapped = { [weak self] in
self?.tappedButton()
}

let contentViewController = UIHostingController(rootView: contentView)

self.addChild(contentViewController)
self.view.addSubview(contentViewController.view)

contentViewController.view.frame = view.bounds
contentViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentViewController.didMove(toParent: self)
}

func tappedButton() {
print("tapped button")
}
}

struct ContentView: View {
var buttonTapped: (() -> Void)?

var body: some View {
Button("Tap me") {
buttonTapped?()
}
}
}
我打电话 buttonTappedWrapperViewController来自 ContentView ,但是这样好吗? “点击按钮”正在打印,但我读了这个 article那说

When you use closures in structs, the closure behaves as a reference type, and the problem starts there. The closures need to have a reference to the environment outside so that the environment can be modified when the closure body is executed.

struct Car {
var speed: Float = 0.0
var increaseSpeed: (() -> ())?
}
var myCar = Car()
myCar.increaseSpeed = {
myCar.speed += 30 // The retain cycle occurs here. We cannot use [weak myCar] as myCar is a value type.
}

那么我应该在这里使用闭包吗?还是我应该做点别的?

最佳答案

We cannot use [weak myCar] as myCar is a value type.


在文章的示例中, myCar是一个结构。
但是,在您的代码中:
contentView.buttonTapped = { [weak self] in
self?.tappedButton()
}
selfUIViewController这是一个类(和一个引用类型)。
您对 [weak self] 的使用非常好:闭包将保持对 UIViewController 的弱引用,当您点击按钮时, tappedButton()函数将被调用。这可能是您所期望的。

关于ios - 可以从托管的 SwiftUI View 调用 UIKit UIViewController 中的闭包吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64624634/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com