IOS 自定义UITextField的输入法

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,weak) UITextField *birthDataText;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIView *accesoryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    accesoryView.backgroundColor = [UIColor redColor];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(60, 0, 200, 40);
    [btn setTitle:@"完成" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [accesoryView addSubview:btn];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 60, 40)];
    [label setText:@"生日: "];
    [label setTextAlignment:NSTextAlignmentRight];
    [self.view addSubview:label];
    
    UITextField *birthDayText = [[UITextField alloc] initWithFrame:CGRectMake(80, 20, 200, 40)];
    [birthDayText setPlaceholder:@"请输入生日"];
    [birthDayText setBorderStyle:UITextBorderStyleRoundedRect];
    [self.view addSubview:birthDayText];
    
    self.birthDataText = birthDayText;
    
    UIDatePicker *dataPicker = [[UIDatePicker alloc] init];
//    [self.view addSubview:dataPicker];
    //选择日期的模式
    [dataPicker setDatePickerMode:UIDatePickerModeDate];
    //NSLog(@"%@",[NSLocale availableLocaleIdentifiers]);
    
    //设置日期控件的初始值
    NSString *startDay = @"2012-12-04";
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    formater.dateFormat = @"yyyy-MM-dd";
    NSDate *date = [formater dateFromString:startDay];
    
    //设置textFiled的默认值
    [self.birthDataText setText:startDay];
    
    [dataPicker setDate:date];
    
    //设置控件显示的地区语言类型
    [dataPicker setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_Hans_CN"]];
    
    //监听日期选择控件的数值变化
    [dataPicker addTarget:self action:@selector(dataChange:) forControlEvents:UIControlEventValueChanged];
    
    //设置输入的UIView,而不是键盘
    [birthDayText setInputView:dataPicker];
    [birthDayText setInputAccessoryView:accesoryView];
}

#pragma mark - 完成按键处理
-(void)btnClick
{
    //退出键盘
    [self.view endEditing:YES];
}

#pragma mark - 日期选择控件的监听方法
-(void)dataChange:(UIDatePicker *)datePicker
{
    NSLog(@"%@",datePicker.date);
    NSDateFormatter *formater = [[NSDateFormatter alloc]init];
    formater.dateFormat = @"yyyy-MM-dd";
    self.birthDataText.text = [formater stringFromDate:datePicker.date];
}

#pragma mark - 点击空白处则退去键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];

}

运行效果


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值