iPhone在UITextField touch上显示日期选择器

时间:2012-06-25 21:48:30

标签: iphone datepicker uitextfield protocols

我遵循了这个帖子:datepicker by clicking on textfield

我导入了以下两种协议:

@interface ViewController : UIViewController<UIActionSheetDelegate, UITextFieldDelegate> {

然后,在实现中,我使用以下内容:

- (void)viewDidLoad {

    textField.delegate = self;

[super viewDidLoad] }

最后,我把实际代码显示日期选择器(来自线程)。我也把它全部联系在IB中。

    //Date Picker
- (void)textFieldDidBeginEditing:(UITextField *)aTextField{    
    [aTextField resignFirstResponder];  

    pickerViewPopup = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];  

    UIDatePicker *pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 0, 0)];  
    pickerView.datePickerMode = UIDatePickerModeDate;  
    pickerView.hidden = NO;  
    pickerView.date = [NSDate date];  

    UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];  
    pickerToolbar.barStyle = UIBarStyleBlackOpaque;  
    [pickerToolbar sizeToFit];  

    NSMutableArray *barItems = [[NSMutableArray alloc] init];  

    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];  
    [barItems addObject:flexSpace];  

    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneButtonPressed:)];  
    [barItems addObject:doneBtn];  

    UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonPressed:)];  
    [barItems addObject:cancelBtn];  

    [pickerToolbar setItems:barItems animated:YES];  

    [pickerViewPopup addSubview:pickerToolbar];  
    [pickerViewPopup addSubview:pickerView];  
    [pickerViewPopup showInView:self.view];  
    [pickerViewPopup setBounds:CGRectMake(0,0,320, 464)];    
}  

-(void)doneButtonPressed:(id)sender{  
    //Do something here here with the value selected using [pickerView date] to get that value  
        [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];  
}  

-(void)cancelButtonPressed:(id)sender{  
    [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];  
}  

但是,当我点击UITextField时,我得到了这个:

enter image description here

我做错了什么?

8 个答案:

答案 0 :(得分:64)

您可以使用UITextField输入视图属性。只需在代码中为init添加一个常规UIDatePicker并将其分配给textfield的inputView。这样做,将显示UIPickerView而不是键盘。如果您需要任何代码,请随时询问:)

编辑:代码

你用{<1>}与IB挂钩

textField

在实施中

@interface myViewController <UITextFieldDelegate>
@property (nonatomic,weak) IBOutlet UITextField *myTextField;
@end 

当您点按UIDatePicker *datePicker = [[UIDatePicker alloc]init]; [datePicker setDate:[NSDate date]]; [datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged]; [self.myTextField setInputView:datePicker]; 时,这会显示UIDatePicker。请注意我添加到datePicker的操作。

textField

每次用户在选择器中滚动时更新textField,您只需要在[datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];

中的某处实现updateTextField方法
viewController

使用最后一种方法,每次用户旋转选择器时,文本字段都会更新!

  • 您可以使用-(void)updateTextField:(id)sender { UIDatePicker *picker = (UIDatePicker*)self.myTextField.inputView; self.myTextField.text = [NSString stringWithFormat:@"%@",picker.date]; } 来改善字符串的输出。

答案 1 :(得分:12)

以下是我显示日期选择器的方式。

- (void)textFieldDidBeginEditing:(UITextField *)textField
{


    self.activeTextField = textField;

    // Create a date picker for the date field.
    UIDatePicker *datePicker = [[UIDatePicker alloc]init];
    datePicker.datePickerMode = UIDatePickerModeDate;
    datePicker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:-31536000];
    [datePicker setDate:[NSDate date]];
    [datePicker addTarget:self action:@selector(updateDateField:) forControlEvents:UIControlEventValueChanged];

    // If the date field has focus, display a date picker instead of keyboard.
    // Set the text to the date currently displayed by the picker.
    if (textField.tag == 1)
    {
    self.date.inputView = datePicker;
    self.date.text = [self formatDate:datePicker.date];
    }   
}


// Called when the date picker changes.
- (void)updateDateField:(id)sender
{
    UIDatePicker *picker = (UIDatePicker*)self.date.inputView;
    self.date.text = [self formatDate:picker.date];
}


// Formats the date chosen with the date picker.
- (NSString *)formatDate:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateFormat:@"MM'/'dd'/'yyyy"];
    NSString *formattedDate = [dateFormatter stringFromDate:date];
    return formattedDate;
}

答案 2 :(得分:3)

@JRo解决方案效果很好!

这是我在Swift 3中更新的代码:

func textFieldDidBeginEditing(_ textField: UITextField) {
    self.activeTextField = textField

    // Create a date picker for the date field.
    let picker = UIDatePicker()
    picker.datePickerMode = .date
    picker.addTarget(self, action: #selector(updateDateField(sender:)), for: .valueChanged)

    // If the date field has focus, display a date picker instead of keyboard.
    // Set the text to the date currently displayed by the picker.
    textField.inputView = picker
    textField.text = formatDateForDisplay(date: picker.date)
}


// Called when the date picker changes.

func updateDateField(sender: UIDatePicker) {
    activeTextField?.text = formatDateForDisplay(date: sender.date)
}


// Formats the date chosen with the date picker.

fileprivate func formatDateForDisplay(date: Date) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "dd MMM yyyy"
    return formatter.string(from: date)
}

答案 3 :(得分:0)

请完成此流程 在.h文件中为UIDatePicker创建对象

UIDatePicker *datePicker;
在.m文件中的

viewDidloadMethod

datePicker = [[UIDatePicker alloc]init];
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.minimumDate = [NSDate date];
[_dateTxtFld setInputView:datePicker];
UIToolbar *toolBar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
[toolBar setTintColor:[UIColor grayColor]];
UIBarButtonItem *doneBtn=[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(showSelectedDate)];
UIBarButtonItem *space=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[toolBar setItems:[NSArray arrayWithObjects:space,doneBtn, nil]];

[_dateTxtFld setInputAccessoryView:toolBar];

之后你可以创建ShowSele

-(void)showSelectedDate {
    if ([_dateTxtFld isFirstResponder]) {
        NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"YYYY-MM-dd"];
        _dateTxtFld.text=[NSString stringWithFormat:@"%@",[formatter stringFromDate:datePicker.date]];
       [_dateTxtFld resignFirstResponder];
    }
   else if ([_timeTxtFld isFirstResponder]) {
   }
}

它对我有用。

答案 4 :(得分:0)

一种不错的方法是制作一个自己的类(我称为TextFieldFormDate),该类派生自UITextField,并封装所有必需的行为。然后,在情节提要中,将文本字段的类设置为TextFieldFormDate(在我的情况下)。

在您的ViewController中使用didChangedidSelect(即使用TextFieldFormDate)来通知更改和实际选择日期。

class TextFieldFormDate: UITextField {

    var date : Date {
        set {
           picker.date = newValue
           text = newValue.localizedDateOnly()
        }

        get {
            return picker.date
        }
    }

    //public handlers
    var didChange : ( (Date)->() )?
    var didSelect : ( (Date)->() )?

    private var picker : UIDatePicker {
        return inputView as! UIDatePicker
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        setup()
    }

    private func setup() {
        font = UIFont.defaultFont()
        //picker for datefield
        inputView = UIDatePicker(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
        picker.datePickerMode = .date
        picker.addTarget(self, action: #selector(pickerChanged), for: .valueChanged)
        let toolBar = UIToolbar()
        toolBar.tintColor = PaintCode.mainBlue
        toolBar.items = [
            UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
            BarBtnPaintCode(type: "done", target: self, action: #selector(didPressDone))
        ]
        toolBar.sizeToFit()
        inputAccessoryView = toolBar
    }

    @objc private func pickerChanged() {
        text = date.localizedDateOnly()
        didChange?(picker.date)
    }

    @objc private func didPressDone() {
        text = date.localizedDateOnly()
        resignFirstResponder()
        didSelect?(picker.date)
    }

}

答案 5 :(得分:0)

Swift 4.2
您可以通过使用UITextField扩展仅编写一行代码来实现此目的。
信用: http://www.swiftdevcenter.com/


import UIKit

extension UITextField {

    func setInputViewDatePicker(target: Any, selector: Selector) {
        // Create a UIDatePicker object and assign to inputView
        let screenWidth = UIScreen.main.bounds.width
        let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216))//1
        datePicker.datePickerMode = .date //2
        self.inputView = datePicker //3

        // Create a toolbar and assign it to inputAccessoryView
        let toolBar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: screenWidth, height: 44.0)) //4
        let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) //5
        let cancel = UIBarButtonItem(title: "Cancel", style: .plain, target: nil, action: #selector(tapCancel)) // 6
        let barButton = UIBarButtonItem(title: "Done", style: .plain, target: target, action: selector) //7
        toolBar.setItems([cancel, flexible, barButton], animated: false) //8
        self.inputAccessoryView = toolBar //9

    }

    @objc func tapCancel() {
        self.resignFirstResponder()
    }

}

在您的UIViewController类中,编写以下代码。


class ViewController: UIViewController {

    @IBOutlet weak var myTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.myTextField.setInputViewDatePicker(target: self, selector: #selector(tapDone(sender:datePicker1:))) //1
    }

    //2
    @objc func tapDone(sender: Any, datePicker1: UIDatePicker) {
        print(datePicker1)
        if let datePicker = self.myTextField.inputView as? UIDatePicker { // 2.1
            let dateformatter = DateFormatter() // 2.2
            dateformatter.dateStyle = .medium // 2.3
            self.myTextField.text = dateformatter.string(from: datePicker.date) //2.4
        }
        self.myTextField.resignFirstResponder() // 2.5
    }

}

有关更多详细信息,请访问: http://www.swiftdevcenter.com/uidatepicker-as-input-view-to-uitextfield-swift/

答案 6 :(得分:0)

这就是我在Swift 4中所做的:

let datePicker = UIDatePicker()
@IBOutlet weak var myTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    setDatePicker()
}

func setDatePicker() {
    //Format Date
    datePicker.datePickerMode = .date

    //ToolBar
    let toolbar = UIToolbar();
    toolbar.sizeToFit()
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneDatePicker));
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelDatePicker));

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

    myTextField.inputAccessoryView = toolbar
    myTextField.inputView = datePicker
}

@objc func doneDatePicker(){
    let formatter = DateFormatter()
    formatter.dateFormat = "MM/dd/yyyy"
    myTextField.text = formatter.string(from: datePicker.date)
    self.view.endEditing(true)
}

@objc func cancelDatePicker(){
    self.view.endEditing(true)
}

答案 7 :(得分:0)

将日期选择器添加到UITextField作为输入视图-Swift代码。希望对大家有帮助。 :)

func addTimePickerToTimeTextFieldView() {

    timePicker = UIDatePicker()
    timePicker?.datePickerMode = .time
    timeTextField.inputView = timePicker

    timePicker?.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
    timePicker?.setValue(#colorLiteral(red: 0.03921568627, green: 0.2352941176, blue: 0.3647058824, alpha: 1), forKeyPath: "textColor")

    timePicker?.addTarget(self, action: #selector(timeSelectedByUser(_:)), for: .valueChanged)

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(viewTapped(_:)))
    view.addGestureRecognizer(tapGesture)

}

@objc func timeSelectedByUser(_ sender: UIDatePicker) {

    let formatter = DateFormatter()
    formatter.timeStyle = .short
    timeTextField.text = formatter.string(from: sender.date)

    //Convert Time for API - 24 hours format
    apiFormatter.dateFormat = "HH:mm"
    timeForApi = apiFormatter.string(from: sender.date)

}