UIToolBar 不使用屏幕的整个宽度

UIToolBar does not use the whole width of the screen

我的 UIToolBar 不想使用整个屏幕宽度。

我不使用任何 TextField,而是将工具栏添加为 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)
}

我也尝试过使用 pickerView.frame.width 作为工具栏宽度,但它似乎无法解决问题。看起来宽度是一些我无法更改的常量值。

同时对工具栏设置约束

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
}