gpt4 book ai didi

在两个类之间快速共享信息

转载 作者:行者123 更新时间:2023-11-30 14:12:55 25 4
gpt4 key购买 nike

我现在正在开发一个选项卡式 View 应用程序,我想知道是否有任何方法可以将我的 FirstViewController.swift 中的信息共享到我的 SecondViewController.swift ?因为我知道 swift 不支持多类继承,所以有没有办法可以在 SecondViewController 中使用 FirstViewController 上的变量和信息?

最佳答案

您需要在 View Controller 上下文之外的模型来存储数据,然后需要一种方法来使用该数据填充这些 View Controller 并提供对模型的引用以从 View Controller 进行更改。您可以通过创建一个符合 UITabBarColtronnerDelegate 的新模型对象来实现此目的,该对象将允许您在选择 View Controller 后访问该 View Controller 。通过将这些关系抽象为协议(protocol)来保持事物的解耦,然后允许您的实现随着应用程序的扩展而独立变化。

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
let applicationModel = ApplicationModel()

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if let tabBarController = window?.rootViewController as? UITabBarController {
tabBarController.delegate = applicationModel
}
return true
}
}

protocol TabbedViewControllerDelegate {
var message: String { set get }
}

class ApplicationModel: NSObject, UITabBarControllerDelegate, TabbedViewControllerDelegate {

var message = "Hello World!"

func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
if var tabbedViewController = viewController as? TabbedViewController {
tabbedViewController.message = message
tabBarController.delegate = self
}
}
}

protocol TabbedViewController {
var message: String { set get }
var delegate: TabbedViewControllerDelegate? { get set }
}

class FirstViewController: UIViewController, TabbedViewController {

var delegate: TabbedViewControllerDelegate?

var message: String = "" {
didSet {
println( "FirstViewController populated with message: \(message)" )
}
}

@IBAction func buttonPressed( sender: AnyObject? ) {
self.delegate?.message = "Updated message from FirstViewController"
}
}

class SecondViewController: UIViewController, TabbedViewController {

var delegate: TabbedViewControllerDelegate?

var message: String = "" {
didSet {
println( "SecondViewController populated with message: \(message)" )
}
}

@IBAction func buttonPressed( sender: AnyObject? ) {
self.delegate?.message = "Updated message from SecondViewController"
}
}

关于在两个类之间快速共享信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31551355/

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