我無法生成一個合適的最小作業示例,主要是由于我對 iOS 開發的新手級理解,但我確實有一個簡單的 SwiftUI 專案可能會有所幫助。
在我的 ContentView.swift 中:
import SwiftUI
struct ContentView: View {
@State var viewText :String
var myClass :MyClass
var body: some View {
VStack{
Text(viewText)
.padding()
Button("Update Text", action: {
myClass.update()
viewText = myClass.txt
})
}
}
}
class MyClass: NSObject {
var txt :String = ""
var useSetVal :Bool = false
func update(){
if(useSetVal){
setValue("used set val", forKey: "txt")
} else {
txt = "used ="
}
useSetVal = !useSetVal
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
let mc = MyClass()
ContentView(viewText: "", myClass: mc)
}
}
在我的 PracticeApp.swift 中
import SwiftUI
@main
struct PracticeApp: App {
var body: some Scene {
WindowGroup {
let mc = MyClass()
ContentView(viewText: "", myClass: mc)
}
}
}
在這個應用程式中,我希望看到“used =”和“used setVal”之間的文本切換作為按下按鈕。相反,當我呼叫 setValue 時出現例外:
Thread 1: "[<Practice.MyClass 0x60000259dc20> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key txt."
我一直在查看這里的答案,但由于大多數答案都涉及 xib 和故事板檔案(我要么沒有,要么不知道如何找到),所以我看不出它們之間的關系。
By the way, even though the app I'm actually trying to fix doesn't use SwiftUI and the issue with setValue is different, it's still true that I either don't have .xib or .storyboard files or I just don't know where to find them.
I'd appreciate help from any one who could either help me figure out the issue with my example, or who can get me closer to solving the issue with my actual app (including how to produce a proper MWE).
I believe what I've already written is sufficient for the issue (at least for a start), but for those interested, I thought I'd add the full story.
The Full Story
我是 iOS 開發的新手,我剛剛擁有了一個舊的 iOS 應用程式。自 2017 年以來就沒有真正接觸過它。我注意到一個影片不起作用。雖然我無法驗證它是否確實有效,但我有充分的理由假設它曾經有效,但我不能說它何時停止作業。我注意到的一個問題是影片屬性應該使用 NSKeyValueCoding.setValue(_:forKey:) 函式進行更新,但在呼叫該函式時似乎沒有任何反應。
我能夠通過用我自己的覆寫 setValue 函式來解決這個問題,該函式基本上使用 switch 陳述句將每個鍵映射到其相應的值。但是,這并沒有修復影片或解釋 setValue 函式不起作用的原因。
因為 setValue 函式和 CABasicAnimation.add(_:forKey:) 都依賴于相同的 keyPath,所以我想知道解決一個問題是否可以幫助我解決另一個問題。我決定關注 setValue 問題(至少現在是這樣)。
當我開始一個新專案用作 MWE 時,我注意到 Xcode 13.0 (13A233) 提供的 Storyboard 和 SwiftUI 界面選項都沒有讓我開始使用與我現有專案匹配的專案結構。我很清楚 SwiftUI 是新的,與我現有的專案非常不同,但故事板界面也不熟悉,在閱讀了幾分鐘的教程后,我未能構建一個完全回應按鈕按下的故事板應用程式(我發現的所有故事板應用程式教程似乎都是為舊版本的 Xcode 設定的)。
uj5u.com熱心網友回復:
SwiftUI 將要求您使用 @ObservedObject 對物件中的更改做出反應。您可以使這符合觀察物件和鍵值操作,如下所示:
struct ContentView: View {
@State var viewText :String
@ObservedObject var myClass :MyClass
var body: some View {
VStack{
Text(viewText)
.padding()
Button("Update Text", action: {
myClass.update()
viewText = myClass.txt
})
}
}
}
class MyClass: NSObject, ObservableObject {
@objc dynamic var txt: String = ""
@Published var useSetVal: Bool = false
func update(){
if(useSetVal){
setValue("used set val", forKey: "txt")
} else {
txt = "used ="
}
useSetVal = !useSetVal
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/316644.html
