Search code examples
iosswiftxcodeuiviewcontrolleruitoolbar

UIToolBar does not use the whole width of the screen


My UIToolBar does not want to use the whole width of the screen.

I do not use any TextField, but adding the toolbar as a sub-view of a UIPickerView.

let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))

@IBAction func addDistanceToCollection(_ sender: UIBarButtonItem) {
        createPickerView()
        createToolBar()
    }

func createPickerView() {
    pickerView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(pickerView)

    pickerView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
    pickerView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
    pickerView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
    pickerView.addSubview(toolBar)
}

func createToolBar() {
    let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: nil)
    let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: nil)
    let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    
    toolBar.sizeToFit()
    toolBar.setItems([cancelButton, flexibleSpace, doneButton], animated: false)
}

I also tried u use pickerView.frame.width as a toolbar width, but it does not seem to fix the problem. Looks like the width is some const value that i just can not change.

enter image description here


Solution

  • Set constraint to toolbar as well

    func createPickerView() {
        pickerView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(pickerView)
        view.addSubview(toolBar)
        
        pickerView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        pickerView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        pickerView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
        
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        toolBar.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        toolBar.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        toolBar.bottomAnchor.constraint(equalTo: pickerView.topAnchor).isActive = true
        toolBar.heightAnchor.constraint(equalToConstant: 50).isActive = true
    }