iOS.UIKit.03.UITextField_UITextView

一、案例介绍:包含UITextField和UITextView,键盘可以打开、关闭,如图01。

图01图02图03

二、案例步骤:

1、选择Single View Application新建项目,取名cq.28.TextField和TextView,如图02。

2、Main.storyboard如图03。

3、CQ28ViewController.h代码

》实现UITextFieldDelegate、UITextViewDelegate,控制软键盘的关闭

#import <UIKit/UIKit.h>

@interface CQ28ViewController : UIViewController<UITextFieldDelegate,UITextViewDelegate>

@end

4、CQ28ViewController.m代码

》键盘打开通知,键盘关闭通知

-(void) viewWillAppear:(BOOL)animated {
    
    //注册键盘出现通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardDidShow:)
                                                 name: UIKeyboardDidShowNotification object:nil];
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardDidHide:)
                                                 name: UIKeyboardDidHideNotification object:nil];
    [super viewWillAppear:animated];
}


-(void) viewWillDisappear:(BOOL)animated {
    //解除键盘出现通知
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: UIKeyboardDidShowNotification object:nil];
    //解除键盘隐藏通知
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: UIKeyboardDidHideNotification object:nil];
    
    [super viewWillDisappear:animated];
}

-(void) keyboardDidShow: (NSNotification *)notif {
    NSLog(@"键盘打开");
}

-(void) keyboardDidHide: (NSNotification *)notif {
    NSLog(@"键盘关闭");
}

》实现委托放弃第一响应者

//通过委托来实现放弃第一响应者
#pragma mark - UITextField Delegate Method
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


//通过委托来实现放弃第一响应者
#pragma mark - UITextView Delegate  Method
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

 

posted @ 2014-06-02 17:10  so_tm_what  阅读(202)  评论(0编辑  收藏  举报