在UITabBarController中的不同选项卡之间共享通用视图

时间:2018-09-02 08:56:20

标签: ios swift uiviewcontroller uitabbarcontroller

我想创建一个由UITabBarController的所有子viewController共享的公共视图。

我试图通过容器视图来实现这一点,但是它为每个子viewController创建了不同的实例。

谢谢!

1 个答案:

答案 0 :(得分:2)

不幸的是,无法在两个不同的超级视图或两个不同的视图控制器(每个视图控制器具有根视图)之间共享视图。

https://developer.apple.com/documentation/uikit/uiview/1622616-addsubview

  

视图只能有一个超级视图。如果视图已经具有超级视图并且该视图不是接收者,则此方法会在使接收者成为新的超级视图之前删除先前的超级视图。

但是您可以通过创建共享数据模型来模拟相同的行为,该共享数据模型包含适当的属性以在不同的视图控制器上显示相同的视图。

struct ViewModel {
    let frame: CGRect
    let backgroundColor: UIColor
    // other properties that identify view state 
}

class FirstViewController: UIViewController {
    var model: ViewModel?

    @IBOutlet weak var customView: UIView! // view that you want to customize from ViewModel. You can create it programmatically.

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let viewModel = model else { return }

        customView.frame = viewModel.frame
        customView.backgroundColor = viewModel.backgroundColor
    }
}

class SecondViewController: UIViewController {
    var model: ViewModel?

    @IBOutlet weak var customView: UIView! // view that you want to customize from ViewModel. You can create it programmatically.

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let viewModel = model else { return }

        customView.frame = viewModel.frame
        customView.backgroundColor = viewModel.backgroundColor
    }
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        // Hierarchy of view controllers is created by storyboard (UITabBarController contains FirstViewController & SecondViewController)
        let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)

        let tabBarController = mainStoryboard.instantiateInitialViewController() as! UITabBarController

        let viewModel = ViewModel(frame: CGRect(x: 10, y: 10, width: 20, height: 20), backgroundColor: UIColor.cyan)
        (tabBarController.viewControllers[0] as! FirstViewController).model = viewModel
        (tabBarController.viewControllers[1] as! SecondViewController).model = viewModel

        window = UIWindow(frame: UIScreen.main.bounds)
        window.rootViewController = tabBarController 

        return true
    }
}