最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
iOS UIDatePicker+UIToolbar时间选择器实例
时间:2022-06-25 23:35:21 编辑:袖梨 来源:一聚教程网
简单的时间选择器,其实就是利用了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
相关文章
- 王者荣耀侦探能力大测试攻略 王者荣耀侦探能力大测试怎么过 11-22
- 无期迷途主线前瞻兑换码是什么 11-22
- 原神欧洛伦怎么培养 11-22
- 炉石传说网易云音乐联动怎么玩 11-22
- 永劫无间手游确幸转盘怎么样 11-22
- 无期迷途主线前瞻兑换码是什么 无期迷途主线前瞻直播兑换码介绍 11-22