gpt4 book ai didi

ios - 在 UITabBarController 中的不同选项卡之间共享公共(public) View

转载 作者:搜寻专家 更新时间:2023-11-01 06:58:13 25 4
gpt4 key购买 nike

我想创建一个由 UITabBarController 的所有 subview Controller 共享的公共(public) View 。

我试图通过容器 View 来实现这一点,但这为每个 subview Controller 创建了不同的实例。

谢谢!

最佳答案

不幸的是,无法在两个不同的父 View 或两个不同的 View Controller 之间共享 View (每个 View Controller 都有 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.

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

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

关于ios - 在 UITabBarController 中的不同选项卡之间共享公共(public) View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52135421/

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