热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

UIDatePicker在按下UIButton之后弹出。-UIDatePickerpopupafterUIButtonispressed

HowcanImakeaUIDatePickerpopup(animated)afteraUIButtonispressed,andthenclosedownaga

How can I make a UIDatePicker pop up (animated) after a UIButton is pressed, and then close down again once the date is selected? This is on the iPhone.

如何在按下UIButton后弹出一个UIDatePicker(动画),然后在选定日期后再次关闭?这是在iPhone上。

5 个解决方案

#1


96  

canihazcode?

Yes, sir. Thanks for helping me procrastinating.

是的,先生。谢谢你帮我拖延。

- (void)changeDate:(UIDatePicker *)sender {
 NSLog(@"New Date: %@", sender.date);
}

- (void)removeViews:(id)object {
 [[self.view viewWithTag:9] removeFromSuperview];
 [[self.view viewWithTag:10] removeFromSuperview];
 [[self.view viewWithTag:11] removeFromSuperview];
}

- (void)dismissDatePicker:(id)sender {
 CGRect toolbarTargetFrame = CGRectMake(0, self.view.bounds.size.height, 320, 44);
 CGRect datePickerTargetFrame = CGRectMake(0, self.view.bounds.size.height+44, 320, 216);
 [UIView beginAnimations:@"MoveOut" context:nil];
 [self.view viewWithTag:9].alpha = 0;
 [self.view viewWithTag:10].frame = datePickerTargetFrame;
 [self.view viewWithTag:11].frame = toolbarTargetFrame;
 [UIView setAnimationDelegate:self];
 [UIView setAnimationDidStopSelector:@selector(removeViews:)];
 [UIView commitAnimations];
}

- (IBAction)callDP:(id)sender {
 if ([self.view viewWithTag:9]) {
  return;
 }
 CGRect toolbarTargetFrame = CGRectMake(0, self.view.bounds.size.height-216-44, 320, 44);
 CGRect datePickerTargetFrame = CGRectMake(0, self.view.bounds.size.height-216, 320, 216);

 UIView *darkView = [[[UIView alloc] initWithFrame:self.view.bounds] autorelease];
 darkView.alpha = 0;
 darkView.backgroundColor = [UIColor blackColor];
 darkView.tag = 9;
 UITapGestureRecognizer *tapGesture = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissDatePicker:)] autorelease];
 [darkView addGestureRecognizer:tapGesture];
 [self.view addSubview:darkView];

 UIDatePicker *datePicker = [[[UIDatePicker alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height+44, 320, 216)] autorelease];
 datePicker.tag = 10;
 [datePicker addTarget:self action:@selector(changeDate:) forControlEvents:UIControlEventValueChanged];
 [self.view addSubview:datePicker];

 UIToolbar *toolBar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height, 320, 44)] autorelease];
 toolBar.tag = 11;
 toolBar.barStyle = UIBarStyleBlackTranslucent;
 UIBarButtonItem *spacer = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
 UIBarButtonItem *dOneButton= [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissDatePicker:)] autorelease];
 [toolBar setItems:[NSArray arrayWithObjects:spacer, doneButton, nil]];
 [self.view addSubview:toolBar];

 [UIView beginAnimations:@"MoveIn" context:nil];
 toolBar.frame = toolbarTargetFrame;
 datePicker.frame = datePickerTargetFrame;
 darkView.alpha = 0.5;
 [UIView commitAnimations];
}

#2


34  

I'd propose the following (good for iOS 3.2 or better).

我的建议如下(适用于iOS 3.2或更好)。

  1. Create a text field.
  2. 创建一个文本字段。
  3. Assign to the text field a inputView that is a UIDateTimerPicker.
  4. 为文本字段分配一个inputView,它是一个UIDateTimerPicker。
  5. When the button is clicked, send a "becomeFirstResponder" event - this will make the date picker slide up from the bottom for you...
  6. 当按钮被单击时,发送一个“becomeFirstResponder”事件——这将使日期选择器从底部滑出。
  7. IMHO, the best way to close the picker is not when a date is picked (since that may close it even as we are searching for the right date/time) - but attach a "Done" or "Select" button as an accessoryInput view to the keyboard.
  8. IMHO,关闭选择器的最佳方式不是选择日期(因为即使我们正在搜索正确的日期/时间,也可能关闭它),而是在键盘上附加一个“完成”或“选择”按钮作为accessoryInput视图。

Below is some code to show steps 2-4: (I hope I didn't forget anything in the copy/paste process...

下面是显示步骤2-4的一些代码:(我希望在复制/粘贴过程中没有忘记任何东西……)

1+3 Creating UIDateTimePicker as the text filed input view, and attaching to it a toolbar with "Done" button...

1+3创建UIDateTimePicker作为文本文件输入视图,并附加一个带有“完成”按钮的工具栏…

    // create a UIPicker view as a custom keyboard view
    UIPickerView* pickerView = [[UIPickerView alloc] init];
    [pickerView sizeToFit];
    pickerView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    pickerView.delegate = self;
    pickerView.dataSource = self;
    pickerView.showsSelectiOnIndicator= YES;

_textField.inputView = pickerView; // _textField must be an instance variable, as you'll need it...

// create a done view + done button, attach to it a doneClicked action, and place it in a toolbar as an accessory input view...
    // Prepare done button
    UIToolbar* keyboardDOneButtonView= [[UIToolbar alloc] init];
    keyboardDoneButtonView.barStyle = UIBarStyleBlack;
    keyboardDoneButtonView.translucent = YES;
    keyboardDoneButtonView.tintColor = nil;
    [keyboardDoneButtonView sizeToFit];

    UIBarButtonItem* dOneButton= [[[UIBarButtonItem alloc] initWithTitle:@"Done"
                    style:UIBarButtonItemStyleBordered target:self
                     action:@selector(doneClicked:)] autorelease];
    [_keyboardDoneButtonView setItems:[NSArray arrayWithObjects:doneButton, nil]];

     // Plug the keyboardDoneButtonView into the text field...
        _textField.inputAccessoryView = keyboardDoneButtonView;

// When the setDate button is clicked, call:

    - (void)setDateClicked:(id)sender {
       [_textField becomeFirstResponder]; 
    }

    - (void)doneClicked:(id)sender {
    // Write out the date...
     [_textField resignFirstResponder];
    }

Good luck...

祝你好运…

#3


3  

Here is a Swift (1.2) version of @Reuven's code

下面是一个Swift(1.2)版本的@Reuven的代码

class ViewController : UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    @IBOutlet var pickerTextField : UITextField!
    var picker : UIPickerView!

    override func viewDidLoad() {
        // create a UIPicker view as a custom keyboard view
        self.picker = UIPickerView()

        if let picker = self.picker {
            picker.sizeToFit()
            picker.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
            picker.delegate = self
            picker.dataSource = self
            picker.showsSelectiOnIndicator= true
            pickerTextField.inputView = picker

            // add a done button
            let toolbar = UIToolbar()
            toolbar.barStyle = UIBarStyle.Black
            toolbar.translucent = true
            toolbar.tintColor = nil
            toolbar.sizeToFit()

            let dOneButton= UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: "dismissPicker")
            toolbar.setItems([doneButton], animated: false)
            pickerTextField.inputAccessoryView = toolbar
        }
    }

    @IBAction func showPicker() {
        pickerTextField.becomeFirstResponder()
    }

    @IBAction func dismissPicker() {
        pickerTextField.resignFirstResponder()
    }
}

#4


2  

- (IBAction)callDP:(id)sender {

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

    [actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];

    CGRect pickerFrame = CGRectMake(0, 40, 0, 0);

    datePickerView = [[UIDatePicker alloc] initWithFrame:pickerFrame];
    datePickerView.tag = 10;
    [datePickerView addTarget:self action:@selector(changeDate:) forControlEvents:UIControlEventValueChanged];

    [actionSheet addSubview:datePickerView];

    UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]];
    closeButton.momentary = YES; 
    closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
    closeButton.segmentedCOntrolStyle= UISegmentedControlStyleBar;
    closeButton.tintColor = [UIColor blackColor];
    [closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
    [actionSheet addSubview:closeButton];
    [closeButton release];


    //[actionSheet showInView:self.view];
    [actionSheet showInView:[UIApplication sharedApplication].keyWindow];

    [actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}

#5


1  

I added some comments for clarity correct me if I'm wrong (I recently started developing for iOS). Thanks Matthias Bauch! Your code example already helped me out a lot and provided lot's of insight. I hope these comments will do the same for others.

我添加了一些清晰的注释来纠正我的错误(我最近开始为iOS开发)。谢谢Matthias胃痛!您的代码示例已经帮助了我很多,并提供了很多见解。我希望这些评论对其他人也能起到同样的作用。

/*
 * Is called when the date is changed by the user.
 */
- (void)changeDate:(UIDatePicker *)sender {
    NSLog(@"New Date: %@", sender.date);
}


/*
 * Releases the background, datepicker and toolbar.
 */
- (void)removeViews:(id)object {

    /*
     *  Releases the background view.
     */ 
    [[self.view viewWithTag:9] removeFromSuperview];
    /*
     *  Releases the datepicker.
     */     
    [[self.view viewWithTag:10] removeFromSuperview];
    /*
     *  Releases the toolbar.
     */     
    [[self.view viewWithTag:11] removeFromSuperview];
}


/*
 * Hides the datapicker.
 */
- (void)dismissDatePicker:(id)sender {

    /*
     * Create a variable with the target position and size for hiding the toolbar.
     */
    CGRect toolbarTargetFrame = CGRectMake(0, self.view.bounds.size.height, 320, 44);
    /*
     * Create a variable with the target position and size for hiding the datepicker.
     */ 
    CGRect datePickerTargetFrame = CGRectMake(0, self.view.bounds.size.height + 44, 320, 216);


    /*
     * Send start animation message to UIView. 
     */ 
    [UIView beginAnimations:@"MoveOut" context:nil];
    /*
     * Set the transparency for hiding the background view.
     */ 
    [self.view viewWithTag:9].alpha = 0;
    /*
     * Set the target position for hiding the datepicker.
     */     
    [self.view viewWithTag:10].frame = datePickerTargetFrame;
    /*
     * Set the target position for hiding the toolbar.
     */     
    [self.view viewWithTag:11].frame = toolbarTargetFrame;
    /*
     * The method setAnimationDelegate enables knowledge on start and end of the animation.
     */         
    [UIView setAnimationDelegate:self];
    /*
     * Calls the removeViews method at the end of the animation.
     */     
    [UIView setAnimationDidStopSelector:@selector(removeViews:)];
    /*
     * Commits the animation thread for execution. 
     */ 
    [UIView commitAnimations];
}


/*
 * Sets up and shows the datepicker.
 */
- (IBAction)callDP:(id)sender {

    /*
     * If view with tag exists ignore the rest of the code and exit.
     */ 
    if([self.view viewWithTag:9]) {
        return;
    }


    /*
     * Create a variable with the target position and size for showing the toolbar.
     */
    CGRect toolbarTargetFrame = CGRectMake(0, self.view.bounds.size.height - 216 - 44, 320, 44);
    /*
     * Create a variable with the target position and size for showing the datepicker.
     */ 
    CGRect datePickerTargetFrame = CGRectMake(0, self.view.bounds.size.height - 216, 320, 216);


    /*
     * Instantiate a UIView with the frame size of the existing view.
     */
    UIView *darkView = [[UIView alloc] initWithFrame:self.view.bounds];
    /*
     * Set the transparency.
     */ 
    darkView.alpha = 0;
    /*
     * Set the background color.
     */ 
    darkView.backgroundColor = [UIColor blackColor];
    /*
     * Set a tag for the UIView instance to reference it by tag.
     */
    darkView.tag = 9;
    /*
     * Setup a tap gesture listener that calls the dismissDatePicker method on tap.
     */     
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissDatePicker:)];
    /*
     * Add the tap gesture listener to the UIView.
     */ 
    [darkView addGestureRecognizer:tapGesture];
    /*
     * Adds the subview on top of all the other subviews.
     */
    [self.view addSubview:darkView];


    /*
     * Instantiate a UIDatePicker and set the initial frame with the datepicker outside of the view.
     */
    UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height+44, 320, 216)];
    /*
     * Set a tag for the UIDatePicker instance to reference it by tag.
     */ 
    datePicker.tag = 10;
    /*
     * Add a listener that listens for changing values in the datepicker which then calls the change date method.
     */     
    [datePicker addTarget:self action:@selector(changeDate:) forControlEvents:UIControlEventValueChanged];
    /*
     * Adds the subview on top of all the other subviews.
     */ 
    [self.view addSubview:datePicker];


    /*
     * Instantiate a UIToolbar and set the initial frame with the toolbar outside of the view.
     */
    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height, 320, 44)];
    /*
     * Set a tag for the UIToolbar instance to reference it by tag.
     */     
    toolBar.tag = 11;
    /*
     * Set a style for the UIToolbar.
     */ 
    toolBar.barStyle = UIBarStyleBlackTranslucent;
    /*
     * Instantiate a spacer UIBarButtonItem.
     */     
    UIBarButtonItem *spacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    /*
     * Instantiate a done UIBarButtonItem on click this will call the dismissDatePicker method.
     */     
    UIBarButtonItem *dOneButton= [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissDatePicker:)];
    /*
     * Set the created UIBarButtonItems to the toolbar.
     */     
    [toolBar setItems:[NSArray arrayWithObjects:spacer, doneButton, nil]];
    /*
     * Adds the subview on top of all the other subviews.
     */ 
    [self.view addSubview:toolBar];


    /*
     * Start animation.
     */ 
    [UIView beginAnimations:@"MoveIn" context:nil];
    /*
     * Set the target position for showing the toolbar.
     */ 
    toolBar.frame = toolbarTargetFrame;
    /*
     * Set the target position for showing the datepicker.
     */     
    datePicker.frame = datePickerTargetFrame;
    /*
     * Set the transparency for showing background view.
     */     
    darkView.alpha = 0.5;
    /*
     * Commits the animation thread for execution. 
     */     
    [UIView commitAnimations];
}

推荐阅读
  • Ihavethefollowingonhtml我在html上有以下内容<html><head><scriptsrc..3003_Tes ... [详细]
  • 使用圣杯布局模式实现网站首页的内容布局
    本文介绍了使用圣杯布局模式实现网站首页的内容布局的方法,包括HTML部分代码和实例。同时还提供了公司新闻、最新产品、关于我们、联系我们等页面的布局示例。商品展示区包括了车里子和农家生态土鸡蛋等产品的价格信息。 ... [详细]
  • 阿里Treebased Deep Match(TDM) 学习笔记及技术发展回顾
    本文介绍了阿里Treebased Deep Match(TDM)的学习笔记,同时回顾了工业界技术发展的几代演进。从基于统计的启发式规则方法到基于内积模型的向量检索方法,再到引入复杂深度学习模型的下一代匹配技术。文章详细解释了基于统计的启发式规则方法和基于内积模型的向量检索方法的原理和应用,并介绍了TDM的背景和优势。最后,文章提到了向量距离和基于向量聚类的索引结构对于加速匹配效率的作用。本文对于理解TDM的学习过程和了解匹配技术的发展具有重要意义。 ... [详细]
  • 拥抱Android Design Support Library新变化(导航视图、悬浮ActionBar)
    转载请注明明桑AndroidAndroid5.0Loollipop作为Android最重要的版本之一,为我们带来了全新的界面风格和设计语言。看起来很受欢迎࿰ ... [详细]
  • FeatureRequestIsyourfeaturerequestrelatedtoaproblem?Please ... [详细]
  • Android开发实现的计时器功能示例
    本文分享了Android开发实现的计时器功能示例,包括效果图、布局和按钮的使用。通过使用Chronometer控件,可以实现计时器功能。该示例适用于Android平台,供开发者参考。 ... [详细]
  • Go GUIlxn/walk 学习3.菜单栏和工具栏的具体实现
    本文介绍了使用Go语言的GUI库lxn/walk实现菜单栏和工具栏的具体方法,包括消息窗口的产生、文件放置动作响应和提示框的应用。部分代码来自上一篇博客和lxn/walk官方示例。文章提供了学习GUI开发的实际案例和代码示例。 ... [详细]
  • 深入理解CSS中的margin属性及其应用场景
    本文主要介绍了CSS中的margin属性及其应用场景,包括垂直外边距合并、padding的使用时机、行内替换元素与费替换元素的区别、margin的基线、盒子的物理大小、显示大小、逻辑大小等知识点。通过深入理解这些概念,读者可以更好地掌握margin的用法和原理。同时,文中提供了一些相关的文档和规范供读者参考。 ... [详细]
  • 在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板
    本文介绍了在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板的方法和步骤,包括将ResourceDictionary添加到页面中以及在ResourceDictionary中实现模板的构建。通过本文的阅读,读者可以了解到在Xamarin XAML语言中构建控件模板的具体操作步骤和语法形式。 ... [详细]
  • 本文详细介绍了如何使用MySQL来显示SQL语句的执行时间,并通过MySQL Query Profiler获取CPU和内存使用量以及系统锁和表锁的时间。同时介绍了效能分析的三种方法:瓶颈分析、工作负载分析和基于比率的分析。 ... [详细]
  • 本文介绍了在处理不规则数据时如何使用Python自动提取文本中的时间日期,包括使用dateutil.parser模块统一日期字符串格式和使用datefinder模块提取日期。同时,还介绍了一段使用正则表达式的代码,可以支持中文日期和一些特殊的时间识别,例如'2012年12月12日'、'3小时前'、'在2012/12/13哈哈'等。 ... [详细]
  • iOS Swift中如何实现自动登录?
    本文介绍了在iOS Swift中如何实现自动登录的方法,包括使用故事板、SWRevealViewController等技术,以及解决用户注销后重新登录自动跳转到主页的问题。 ... [详细]
  • IOS开发之短信发送与拨打电话的方法详解
    本文详细介绍了在IOS开发中实现短信发送和拨打电话的两种方式,一种是使用系统底层发送,虽然无法自定义短信内容和返回原应用,但是简单方便;另一种是使用第三方框架发送,需要导入MessageUI头文件,并遵守MFMessageComposeViewControllerDelegate协议,可以实现自定义短信内容和返回原应用的功能。 ... [详细]
  • JavaScript和HTML之间的交互是经由过程事宜完成的。事宜:文档或浏览器窗口中发作的一些特定的交互霎时。能够运用侦听器(或处置惩罚递次来预订事宜),以便事宜发作时实行相应的 ... [详细]
  • 本文介绍了pack布局管理器在Perl/Tk中的使用方法及注意事项。通过调用pack()方法,可以控制部件在显示窗口中的位置和大小。同时,本文还提到了在使用pack布局管理器时,应注意将部件分组以便在水平和垂直方向上进行堆放。此外,还介绍了使用Frame部件或Toplevel部件来组织部件在窗口内的方法。最后,本文强调了在使用pack布局管理器时,应避免在中间切换到grid布局管理器,以免造成混乱。 ... [详细]
author-avatar
520sweet跃_322
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有