在 UITabBarController 中的不同选项卡之间共享公共视图 [英] Sharing common view between different tabs in UITabBarController
问题描述
我想创建一个由 UITabBarController 的所有子视图控制器共享的公共视图.
I want to create a common view which is shared by all the child viewControllers of a UITabBarController.
我试图通过容器视图来实现这一点,但这为每个子视图控制器创建了不同的实例.
I tried to achieve this by container view but that creates different instances for each child viewControllers.
谢谢!
推荐答案
遗憾的是,无法在两个不同的超视图或两个不同的视图控制器(每个视图控制器都有根视图)之间共享视图.
Unfortunately, there is no way to share view between two different superviews or two different view controllers (each view controller has root view).
https://developer.apple.com/documentation/uikit/uiview/1622616-addsubview
视图只能有一个超级视图.如果视图已经有一个超视图并且该视图不是接收器,则此方法会在使接收器成为新的超视图之前删除之前的超视图.
Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.
但是您可以通过创建包含适当属性的共享数据模型来模拟相同的行为,以在不同的视图控制器上显示相同的视图.
But you can simulate the same behaviour by making shared data model that contains appropriate properties to display identical view on different view controllers.
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
}
}
这篇关于在 UITabBarController 中的不同选项卡之间共享公共视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!