I set done and cancel button on my UIDatePicker within a toolbar programmatically. However, I could not detect click actions for done and cancel buttons. I could not find the cause of the issue. Here is my code:
@IBAction func btnDueDate_Click(sender: UIButton)
{
var toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
toolBar.sizeToFit()
var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("Done_Click"))
var spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("Cancel_Click"))
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
self.datePicker.addSubview(toolBar)
self.datePicker.hidden = false
}
func Done_Click()
{
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
self.btnDueDate.setTitle(dateFormatter.stringFromDate(self.datePicker.date), forState: UIControlState.Normal)
}
func Cancel_Click()
{
self.datePicker.hidden = true
}
Could you help me about what am I doing wrong ?
Thank you for your answers
Best regards
Solved: Thank u for your help, I've solved the problem by editting the code line below:
self.view.addSubview(toolBar)
When I add the toolbar as a subview of self.view, not as a subview of self.datePicker, It works fine.
The reason why your code isn't working is because the
UIToolbaris overlapping theUIDatePickerand the picker is receiving all of the inputs.I would suggest for you to use the property
inputAccessoryViewand assign the toolbar to this, but unfortunately, this is a read-only property for both theUIButtonandUIDatePickerA work-around which many people are using is to use a
UITextFieldand set theinputViewto aUIDatePickerand theinputAccessoryViewto aUIToolbar. I've made a small example underneath that you can try out.