How to add a UIToolbar programmatically to an iOS app?

后端 未结 7 1091
太阳男子
太阳男子 2020-12-04 10:01

Can\'t seem to find a tutorial which does as the question title describes. I\'d like to understand just where the UIToolbar needs to be declared and how to get it onto my vi

7条回答
  •  一生所求
    2020-12-04 10:42

    iOS 11+ SWIFT 4 + Xcode 9 + Constraints

    Works for both landscape + Portrait

        override func viewDidLoad() {
            super.viewDidLoad()
            print(UIApplication.shared.statusBarFrame.height)//44 for iPhone x, 20 for other iPhones
            navigationController?.navigationBar.barTintColor = .red
    
    
            let toolBar = UIToolbar()
            var items = [UIBarButtonItem]()
            items.append(
                UIBarButtonItem(barButtonSystemItem: .save, target: nil, action: nil)
            )
            items.append(
                UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(tapsOnAdd))
            )
            toolBar.setItems(items, animated: true)
            toolBar.tintColor = .red
            view.addSubview(toolBar)
    
            toolBar.translatesAutoresizingMaskIntoConstraints = false
    
    
            if #available(iOS 11.0, *) {
                let guide = self.view.safeAreaLayoutGuide
                toolBar.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
                toolBar.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
                toolBar.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
                toolBar.heightAnchor.constraint(equalToConstant: 44).isActive = true
    
            }
            else {
                NSLayoutConstraint(item: toolBar, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
                NSLayoutConstraint(item: toolBar, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
                NSLayoutConstraint(item: toolBar, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
    
                toolBar.heightAnchor.constraint(equalToConstant: 44).isActive = true
            }
    
        }
    

提交回复
热议问题