- #import "ViewController.h"
- @interface ViewController ()<UITextFieldDelegate>
- {
- UITextField *_commentTextField;
- }
- @end
- @implementation ViewController
- - (void)viewDidLoad {
- [super viewDidLoad];
- //键盘通知
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
- //实例化输入框
- _commentTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height-35, [UIScreen mainScreen].bounds.size.width, 32)];
- [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector (textFieldChange:)
- name:UITextFieldTextDidChangeNotification object:_commentTextField];
- _commentTextField.borderStyle = UITextBorderStyleRoundedRect;
- _commentTextField.returnKeyType = UIReturnKeyDone;
- _commentTextField.enablesReturnKeyAutomatically = YES;
- _commentTextField.placeholder = @"请输入 王木木 点击完成";
- _commentTextField.backgroundColor = [UIColor whiteColor];
- _commentTextField.delegate = self;
- [self.view addSubview:_commentTextField];
- self.view.backgroundColor = [UIColor blueColor];
- }
- - (void)btn{
- NSLog(@"dsfa");
- }
- #pragma mark - 键盘 改变通知 弹键盘
- -(void)keyboardWasChange:(NSNotification *)notification
- {
- NSDictionary *info = [notification userInfo];
- if ([[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y != [UIScreen mainScreen].bounds.size.height) {
- _commentTextField.frame = CGRectMake(0, [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y-45, [UIScreen mainScreen].bounds.size.width, 45);
- }else {
- _commentTextField.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 45, [UIScreen mainScreen].bounds.size.width, 45);
- }
- }
- //点击界面view 触发 收键盘
- - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
- [_commentTextField resignFirstResponder];
- _commentTextField.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 45, [UIScreen mainScreen].bounds.size.width, 45);
- }
- -(void)textFieldChange:(NSNotification *)notification
- {
- UITextField *textField=[notification object];
- NSString *lang = [textField.textInputMode primaryLanguage]; // 键盘输入模式
- if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入,包括简体拼音,健体五笔,简体手写
- UITextRange *selectedRange = [textField markedTextRange];
- //获取高亮部分
- UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
- // 没有高亮选择的字,则对已输入的文字进行字数统计和限制
- if (!position) {
- if ([textField.text isEqualToString:@"王木木"]) {
- UIAlertView *ale = [[UIAlertView alloc]initWithTitle:@"我爱你" message:nil delegate:nil cancelButtonTitle:@"谢谢" otherButtonTitles: nil];
- [ale show];
- }
- }
- }
- }
- - (void)didReceiveMemoryWarning {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- @end
来源: http://www.phpxs.com/code/1006517/