我正在尝试将uiView从SpritzSwift实现到SwiftUI应用程序,但是在第一次呈现之后,我无法让它更新。驱动UIView的管理器正在工作,但UIView本身没有更新。我希望视图控制器中的UiView.setNeedsDisplay()或者包装器中@Bindable变量中的更改会触发updateUIView,但不会触发骰子。
无论我对UiView或它的包装做了什么更改,它都不会被更新(例如,在代码示例中,背景永远不会被更新以清除颜色)。如何更新此视图?
以下是SwiftUI代码:
import SwiftUI
struct Content: View {
@State public var ssManager:SpritzSwiftManager = SpritzSwiftManager(withText: "", andWordPerMinute: Int(200))
@State public var ssView:SpritzSwiftView = SpritzSwiftView(frame: CGRect(x: 0, y: 0, width: 200, height: 600 ))
@State private var currentWord = ""
var body: some View {
VStack {
Text("SpritzTest")
.padding()
let spritzUIView = SpritzUIViewRepresentable(SpritzView: $ssView,SpritzViewManager:$ssManager, CurrentWord: $currentWord)
spritzUIView.padding()
Button(action:
{
ssManager = SpritzSwiftManager(withText: "Text try one two three", andWordPerMinute: 200)
spritzUIView.SpritzView = SpritzSwiftView(frame: CGRect(x: 0, y: 0, width: 200, height: 40 ))
spritzUIView.SpritzView.backgroundColor = .clear
ssManager.startReading { (word, finished) in
if !finished {
self.ssView.updateWord(word!)
currentWord = word!.word
spritzUIView.CurrentWord = currentWord
}
}
})
{
Text("Start")
}
}
}
}包装是这样的:
struct SpritzUIViewRepresentable : UIViewRepresentable{
@Binding var SpritzView:SpritzSwiftView
@Binding var SpritzViewManager:SpritzSwiftManager
@Binding var CurrentWord:String
func makeUIView(context: Context) -> SpritzSwiftView {
return SpritzView
}
func updateUIView(_ uiView: SpritzSwiftView, context: Context) {
}
}发布于 2020-12-27 04:12:36
您需要在UIKit中创建makeUIView视图,并通过绑定传递仅依赖的数据。当相关的状态-真相来源发生变化时,绑定更改调用updateUIView,在那里您应该更新您的UIKit视图。
这里仅提供简化的演示草图,以显示概念(可能有排印):
struct SpritzUIViewRepresentable : UIViewRepresentable{
@Binding var currentWord: SpritzSwiftWord
@Binding var backgroundColor: UIColor
func makeUIView(context: Context) -> SpritzSwiftView {
// create and configure view here
return SpritzSwiftView(frame: CGRect.zero) // frame does not matter here
}
func updateUIView(_ uiView: SpritzSwiftView, context: Context) {
// update view properties here from bound external data
uiView.backgroundColor = backgroundColor
uiView.updateWord(currentWord)
}
}按钮现在只需更改模型数据。
VStack {
Text("SpritzTest")
.padding()
SpritzUIViewRepresentable(backgroundColor: $backgroundColor, SpritzViewManager:$ssManager, currentWord: $currentWord)
.padding()
Button(action:
{
ssManager = SpritzSwiftManager(withText: "Text try one two three", andWordPerMinute: 200)
self.backgroundColor = .clear
ssManager.startReading { (word, finished) in
if !finished {
self.currentWord = word
}
}
})
{
Text("Start")
}假设更新的属性
@State private var currentWord = SpritzSwiftWord(word: "")
@State private var backgroundColor = UIColor.white // whatever you wanthttps://stackoverflow.com/questions/65461516
复制相似问题