How do I programmatically add a view right under the navigation bar?

前端 未结 6 886
轻奢々
轻奢々 2021-02-04 11:25

I\'m trying to add a view to a UINavigationController with its top aligned with the navigation bar\'s bottom.

I tried using constraints by adding the follo

6条回答
  •  迷失自我
    2021-02-04 11:54

    Swift

    Try this code with NSLayoutConstraint. newView will appear right under NavigationBar

            self.edgesForExtendedLayout = []//Optional our as per your view ladder
    
            let newView = UIView()
            newView.backgroundColor = .red
            self.view.addSubview(newView)
            newView.translatesAutoresizingMaskIntoConstraints = false
            if #available(iOS 11.0, *) {
                let guide = self.view.safeAreaLayoutGuide
                newView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
                newView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
                newView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
                newView.heightAnchor.constraint(equalToConstant: 50).isActive = true
            } else {
                NSLayoutConstraint(item: newView,
                                   attribute: .top,
                                   relatedBy: .equal,
                                   toItem: view, attribute: .top,
                                   multiplier: 1.0, constant: 0).isActive = true
                NSLayoutConstraint(item: newView,
                                   attribute: .leading,
                                   relatedBy: .equal, toItem: view,
                                   attribute: .leading,
                                   multiplier: 1.0,
                                   constant: 0).isActive = true
                NSLayoutConstraint(item: newView, attribute: .trailing,
                                   relatedBy: .equal,
                                   toItem: view,
                                   attribute: .trailing,
                                   multiplier: 1.0,
                                   constant: 0).isActive = true
    
                    newView.heightAnchor.constraint(equalToConstant: 50).isActive = true
            }
        
    

提交回复
热议问题