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



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

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

谢谢!

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

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
}
}

相关内容

  • 没有找到相关文章

最新更新