How to make an UIPickerView with a Done button?

前端 未结 5 1828
天涯浪人
天涯浪人 2020-12-22 16:31

I am having difficulties to make an UIPickerView with a done button to appear when the users taps a UITextField. This is my code so far. Everything builds fine, but when I t

5条回答
  •  借酒劲吻你
    2020-12-22 17:26

    Add this code to your viewDidLoad() instead of method

    let picker: UIPickerView
    picker = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 300))
    picker.backgroundColor = .whiteColor()
    
    picker.showsSelectionIndicator = true
    picker.delegate = self
    picker.dataSource = self
    
    let toolBar = UIToolbar()
    toolBar.barStyle = UIBarStyle.default
    toolBar.isTranslucent = true
    toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
    toolBar.sizeToFit()
    
    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, target: self, action: #selector(self. donePicker))
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItem.Style.plain, target: self, action: #selector(self. donePicker))
    
    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolBar.userInteractionEnabled = true
    
    textField1.inputView = picker
    textField1.inputAccessoryView = toolBar
    

提交回复
热议问题