最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
iOS UIDatePicker+UIToolbar时间选择器实例
时间:2016-08-15 编辑:简简单单 来源:一聚教程网
简单的时间选择器,其实就是利用了UITextField的inputView属性。直接看代码:
#import "ViewController.h"
@interface ViewController ()
UITextField *textFiled;
NSString *timeStr;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
textFiled = [[UITextField alloc] initWithFrame:CGRectMake(70, 80, 120, 30)];
textFiled.layer.borderColor = [[UIColor grayColor]CGColor];
textFiled.layer.border.0f;
[self.view addSubview:textFiled];
//添加一个时间选择器
UIDatePicker *datePicker = [[UIDatePicker alloc]init];
//设置只显示中文
[datePicker setLocale:[NSLocale localeWithLocaleIdentifier:@"zh-CN"]];
//添加滚动事件
[datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
//设置只显示日期
datePicker.datePickerMode = UIDatePickerModeDate;
//当光标移动到文本框的时候,召唤时间选择器
textFiled.inputView = datePicker;
//创建工具条
UIToolbar *toolbar = [[UIToolbar alloc]init];
//设置工具条的颜色
toolbar.barTintColor = [UIColor blackColor];
//设置工具条的frame
toolbar.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 35);
//给工具条添加按钮
UIBarButtonItem *item0 = [[UIBarButtonItem alloc]initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:nil];
UIBarButtonItem *item1 = [[UIBarButtonItem alloc]initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:nil];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *item3 = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
toolbar.items = @[item0,item1,item2,item3];
//设置文本输入框键盘的辅助视图
textFiled.inputAccessoryView = toolbar;
}
#pragma mark - 时间选择
-(void)dateChanged:(UIDatePicker *)sender{
NSDate *date = sender.date;
NSDateFormatter *yearDateFormatter = [NSDateFormatter new];
yearDateFormatter.dateFormat = @"yyyy";
NSDateFormatter *monthDateFormatter = [NSDateFormatter new];
monthDateFormatter.dateFormat = @"MM";
NSDateFormatter *dayDateFormatter=[NSDateFormatter new];
[dayDateFormatter setDateFormat:@"dd"];
timeStr = [NSString stringWithFormat:@"%@-%@-%@",[yearDateFormatter stringFromDate:date],[monthDateFormatter stringFromDate:date],[dayDateFormatter stringFromDate:date]];
}
#pragma mark - 确定按钮点击
-(void)click:(UIButton *)sender
{
NSLog(@"timeStr>=%@",timeStr);
textFiled.text = timeStr;
[textFiled resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
-
上一个: iOS 获取某年某月的天数的示例
-
下一个: 免费下载qq音乐付费歌曲音乐的方法
相关文章
- sora软件价格介绍 02-22
- sora官网入口地址一览 02-22
- Sora生成的视频使用教程 02-22
- 《梦幻西游》元宵灯谜线索答案大全2024 02-22
- 《原神》有朋自远方来第一天通关攻略 02-22
- 《苏醒之路》四个结局达成攻略 02-22