【发布时间】:2021-02-16 17:11:59
【问题描述】:
在 Stroyboard 中,将 UIViewController 嵌入到导航控制器中非常简单,然后可以添加 UIBarButtonItem 取消按钮,用于展开目的。
但是,我想知道,如果我们的 UIViewController 是从 XIB 创建的,我们该怎么做?
我有以下自定义视图,它呈现模态 UIViewController。
class CustomColorView: UIView {
@objc func textViewWasTapped() {
let hexColorStringInputVC = HexColorStringInputVC.instanceFromNib()
let navController = UINavigationController(rootViewController: hexColorStringInputVC)
// Cancel button not visible. Not sure why?!
navController.navigationItem.setLeftBarButton(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: nil), animated: true)
UIViewController.topViewController()?.present(navController, animated: true, completion: nil)
}
...
}
extension UIViewController {
static func instanceFromNib() -> Self {
func instantiateFromNib<T: UIViewController>() -> T {
return T.init(nibName: String(describing: T.self), bundle: nil)
}
return instantiateFromNib()
}
static func topViewController() -> UIViewController? {
let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
guard var top = keyWindow?.rootViewController else {
return nil
}
while let next = top.presentedViewController {
top = next
}
return top
}
}
textViewWasTapped 执行时,如下所示。
- 是否需要在
UINavigationController中嵌入UIViewController? - 为什么通过
navController.navigationItem.setLeftBarButton看不到左上角的取消按钮? - 如何在导航取消按钮上添加展开操作?
- 在 XIB 中是否有更简单的操作,就像 Storyboard 一样简单?
【问题讨论】: