I'd like to show a custom date picker keyboard when tapping a Toolbar button (UIBarButtonItem).
For showing custom keyboards using aa UIResponder
's inputView
seems to be the right choice. Unfortunatelly the UIBarButtonItem isn't a subclass of UIResponder.
How can I have a UIBarButtonItem becomeFirstResponder and carry an inputView to show such a keyboard?
Why do you want to show keyboard when user taps on UIBarButtonItem? Suppose keyboard is shown on tap of UIBarButtonItem, what will happen when user types in something using keyboard? Which control is expected to receive key press events from keyboard?
Instead of inputView approach, you can follow another approach to show datePicker on button click
Let showDatePicker
is the method called on button click then
-(void)showDatePicker
{
UIDatePicker* picker = [[UIDatePicker alloc] init];
picker.autoresizingMask = UIViewAutoresizingFlexibleWidth;
picker.datePickerMode = UIDatePickerModeDate;
[picker addTarget:self action:@selector(dueDateChanged:) forControlEvents:UIControlEventValueChanged];
CGSize pickerSize = [picker sizeThatFits:CGSizeZero];
picker.frame = CGRectMake(0.0, 250, pickerSize.width, 460);
picker.backgroundColor = [UIColor blackColor];
[self.view addSubview:picker];
}
-(void) dueDateChanged:(UIDatePicker *)sender {
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
//self.myLabel.text = [dateFormatter stringFromDate:[dueDatePickerView date]];
NSLog(@"Picked the date %@", [dateFormatter stringFromDate:[sender date]]);
}
To remove the datePicker , you can use removeFromSuperView
on either method called from another button click in your View or your custom toolbar
done button.
I've accomplished this by creating a UITextField
let myPicker = UIPickerView()
lazy var pickerInputField: UITextField = {
let field = UITextField(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
self.view.addsubview(field)
field.delegate = self
return field
}()
func barButtonItemTouched(sender: Any) {
// dismiss the picker if it's showing
if pickerInputField.isFirstResponder {
pickerInputField.resignFirstResponder()
}
pickerInputField.inputView = myPicker
pickerInputField.becomeFirstResponder()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.