[英]How to properly implement protocols and delegates between different view controllers in Swift?
[英]How to implement protocols and delegates in SwiftUI
我正在將我的 swift 項目之一轉換為 SwiftUI。 我需要將委托和協議轉換為 SwiftUI,SwiftUI 是否允許? 或有任何替代方法嗎? 請幫助我,我對 SwiftUI 感到很困惑。
我從我的 class 之一調用委托方法,然后委托方法將出現在另一個 ViewController 中。
//PresenterClass
protocol SplashPresenterDelegate {
func didFetchedSystemInfo(info: String)
}
class SplashPresenter: NSObject {
var delegate: SplashPresenterDelegate?
func getSystemInfo(){
self.delegate?.didFetchedSystemInfo(info: "ResponseString")
}
}
// Viewcontroller class
class myViewController: UIViewController {
.
.
.
}
extension myViewController: SplashPresenterDelegate{
func didFetchedSystemInfo(info: String){
print("delegate called")
}
}
請幫我將此代碼轉換為 SwiftUI
通常,SwiftUI 更喜歡采用回調而不是協議/委托的模式。 例如, ActionSheet
中的每個按鈕都有一個在點擊按鈕時執行的閉包。
不過,您不應該直接轉換您的代碼。 SwiftUI 是聲明性的,對很多事情使用不同的范例。 例如,您不會有一個didFetchInfo
方法,您只需將它分配給一個 @Published 變量。
考慮擁有“單一事實來源”,其中一個變量始終是正確的。 例如, List
只需獲取一個數組並在數組更改時進行更新,這與UITableView
不同,您通過numberOfRows
和cellForRowAt
提供數據。 我對您的具體項目了解得不夠多,無法提供更多細節,但這些都是需要考慮的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.