UITextField 离开输入框 关闭虚拟键盘

2011-07-10

小小的技巧,一开始想的太复杂了。呵呵 由于我对IB的感冒,所以只能用Xcode实现了。呵呵

// TestViewController.h
#import 

@interface TestViewController : UIViewController {

    UITextField * UNtextField;
    UITextField * PWtextField;
    
}

@property (nonatomic, retain) UITextField * UNtextField;
@property (nonatomic, retain) UITextField * PWtextField;

@end

// TestViewController.m
@implementation TestViewController

@synthesize UNtextField;
@synthesize PWtextField;

- (void)loadView
{
    [super loadView];


    UIButton * hidebtn = [UIButton buttonWithType:UIButtonTypeCustom];
    hidebtn.frame = frame;
    [hidebtn setBackgroundColor:[UIColor grayColor]];
    [hidebtn setOpaque:YES];
    [hidebtn addTarget:self action:@selector(hideKeyboard:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:hidebtn];

    UNtextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 120, 280, 30)];
    UNtextField.borderStyle = UITextBorderStyleRoundedRect;
    UNtextField.textColor = [UIColor blackColor];
    UNtextField.font = [UIFont systemFontOfSize:17.0];
    UNtextField.placeholder = @"Enter Your name";
    UNtextField.autocorrectionType = UITextAutocorrectionTypeNo;
    UNtextField.backgroundColor = [UIColor clearColor];
    UNtextField.keyboardType = UIKeyboardTypeDefault;
    UNtextField.returnKeyType = UIReturnKeyDone;
    UNtextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        
    [self.view addSubview:UNtextField];
        
    PWtextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 160, 280, 30)];
    PWtextField.borderStyle = UITextBorderStyleRoundedRect;
    PWtextField.secureTextEntry = YES;
    PWtextField.font = [UIFont systemFontOfSize:17.0];
    PWtextField.placeholder = @"Enter Your password";
    PWtextField.autocorrectionType = UITextAutocorrectionTypeNo;
    PWtextField.backgroundColor = [UIColor clearColor];
    PWtextField.keyboardType = UIKeyboardTypeDefault;
    PWtextField.returnKeyType = UIReturnKeyGo;
    PWtextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:PWtextField];
}

-(void)hideKeyboard:(id)sender
{
    [UNtextField resignFirstResponder];
    [PWtextField resignFirstResponder];
}

- (void)dealloc
{
    [UNtextField release];
    [PWtextField release];
    [super dealloc];
}
@end