【问题标题】:How to add title/button to a UINavigationController added inside a UIViewController?如何将标题/按钮添加到 UIViewController 中添加的 UINavigationController?
【发布时间】:2016-04-01 03:28:51
【问题描述】:

由于某种原因,我必须在 UIViewController() 中添加一个 UINavagationController(),所以我在视图控制器类中做了以下操作:

class someViewController: UIViewController {
    private let myNav = UINavigationController()
    override func viewDidLoad() {
        self.addChildViewController(myNav)
        self.view.addSubview(myNav.view)
        myNav.view.translatesAutoresizingMaskIntoConstraints = false
        myNav.view.topAnchor.constraintEqualToAnchor(self.topLayoutGuide.bottomAnchor).active = true
        myNav.view.leftAnchor.constraintEqualToAnchor(view.leftAnchor).active = true
        myNav.view.rightAnchor.constraintEqualToAnchor(view.rightAnchor).active = true
        myNav.view.heightAnchor.constraintEqualToAnchor(nil, constant: 44).active = true
        myNav.didMoveToParentViewController(self)
    }
}

导航控制器已添加并正确显示。然后我尝试向导航栏添加标题(或完成按钮),但是这些项目没有显示出来。我尝试了一些这样的事情:

self.navigationItem.title = "some title"
myNav.navigationItem.title = "some title"
myNav.navigationItem.rightBarButtonItem = btnDone

在这种情况下,正确的做法是什么?

【问题讨论】:

    标签: ios objective-c swift uiviewcontroller uinavigationcontroller


    【解决方案1】:

    为什么不用这个简单的代码来添加导航栏:

        let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 66)) // Offset by 20 pixels vertically to take the status bar into account
    
    
        // Create a navigation item with a title
        let navigationItem = UINavigationItem()
        navigationItem.title = "Title"
    
        // Create left and right button for navigation item
        let leftButton =  UIBarButtonItem(title: "Save", style:   UIBarButtonItemStyle.Plain, target: self, action: "btn_clicked:")
        let rightButton = UIBarButtonItem(title: "Right", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
    
        // Create two buttons for the navigation item
        navigationItem.leftBarButtonItem = leftButton
        navigationItem.rightBarButtonItem = rightButton
    
        // Assign the navigation item to the navigation bar
        navigationBar.items = [navigationItem]
    
        // Make the navigation bar a subview of the current view controller
        self.view.addSubview(navigationBar)
    

    【讨论】:

    • 谢谢。我知道这种方式,但是当我使用UINavigationBar 方法时,我无法使顶角变圆。我在 SO 中找到了一个解决方案,但是当我使用 CAShapeLayer 解决方案将顶角变为圆形时,标题/按钮会以某种方式消失。所以我尝试再次探索UINavigationController 选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 2015-08-03
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    相关资源
    最近更新 更多