一旦实例化,请尽快做某事
这似乎是一个简单的问题,但是我无法在Swift文档中找到任何解决方案。当我在Kotlin进行编程时,通常使用类的init()
方法来执行一些工作,以便进行类设置并准备好使用。
现在,我正在创建一个uiviewRementable
,并想在初始化此结构后立即做某事。似乎init()
用于结构的方法仅与成员初始化有关。
例如,.onappear
view
提供此功能如下:
struct MapView: View {
@StateObject private var viewModel = MapViewModel()
var body: some View {
Map(coordinateRegion: $viewModel.region,
interactionModes: .all,
showsUserLocation: true)
.onAppear {
// this will occur as soon as the View appears
viewModel.safeCreateLocationManager()
}
}
}
但是现在,当定义uiviewReprementable
struct时,我希望执行相同的:
struct OverlayMapView: UIViewRepresentable {
@StateObject private var viewModel = MapViewModel()
// immediately do the following:
viewModel.safeCreateLocationManager()
func makeUIView(context: Context) -> MKMapView {
...
}
func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<OverlayMapView>) {
...
}
}
This seems like a straightforward question, but I have not been able to find any solutions in the Swift docs. When I was programming in Kotlin, it was common to use the init()
method of a class to perform some work in order to get the class set up and ready for use.
Now I am creating a UIViewRepresentable
and would like to do something as soon as this struct is initialized. It seems that the init()
method for structs is only concerned with member initialization.
For example, the .onAppear
method for a View
provides this functionality as follows:
struct MapView: View {
@StateObject private var viewModel = MapViewModel()
var body: some View {
Map(coordinateRegion: $viewModel.region,
interactionModes: .all,
showsUserLocation: true)
.onAppear {
// this will occur as soon as the View appears
viewModel.safeCreateLocationManager()
}
}
}
But now when defining a UIViewRepresentable
struct I am wishing to do the same:
struct OverlayMapView: UIViewRepresentable {
@StateObject private var viewModel = MapViewModel()
// immediately do the following:
viewModel.safeCreateLocationManager()
func makeUIView(context: Context) -> MKMapView {
...
}
func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<OverlayMapView>) {
...
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是可能的,但是不正确的(因此我甚至不会告诉),而是使用它
*
makeuiview
是在init
in 之前呼叫onappear
It is possible but would be not correct (so I will not tell even how), instead use it
*the
makeUIView
is called afterinit
and beforeonAppear