Constraints error when using a UIPickerView

Viewed 714

Whenever I click on one of the pickerviews that I create, I get the following error logged to the console:

[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)

I know that this error usually happens when there are conflicting constraints but I don't see what the conflicting constraints would be in this case. The pickerview still works correctly but I still would like to get rid of this error.

code:

@IBAction func showDatePicker(_ sender: PickerField){
        let datePicker = UIDatePicker
        let datePickerField = sender



        datePicker.translatesAutoresizingMaskIntoConstraints = false
        datePicker.datePickerMode = .time

        let toolbar = UIToolbar()
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        toolbar.sizeToFit()
        let finishedButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(donedatePicker))
        finishedButton.tag = sender.tag
        let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
        let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelDatePicker))
        cancelButton.tag = sender.tag

        toolbar.setItems([cancelButton,spaceButton,finishedButton], animated: false)

        datePickerField.inputView = datePicker
        datePickerField.inputAccessoryView = toolbar
    }

(FYI, I've tried turning translatesAutoResizingMaskIntoConstraints on and off for both the picker and toolbar and the error still occurs)

1 Answers

The constraint error is caused by the UIToolBar. It appears to be an issue with the current OS. To silence the warning, initialize the UIToolbar a specified width of 100, it will still stretch to the borders.

let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 100.0, height: 44.0))

You don't need to use .sizeToFit(), nor .translatesAutoresizingMaskIntoConstraints = false

Related