본문 바로가기

Apple - IPhone / IPod Touch

iPhone 키보드 닫기 done 버튼 추가


// Notification 을 사용하기 위해서 NotificationCenter에 특정 메시지를 등록해놓아야 한다.
// 등록된 메시지 (여기서는 UIKeyboardWillShowNotification)가 불려지면 등록된 옵저버는
그것을 감지하고 selector를 이용해서 그것을 처리할 메소드를 부른다.

- (void)viewDidLoad {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [super viewDidLoad];
}


// 위에서 키보드가 나타나기 직전에 keyboardWillShow:메소드가 불리도록 등록해놨다.
// 여기서 키보드뷰에 툴바뷰를 붙인다.
- (void)keyboardWillShow:(NSNotification *)notification
{   
    for (UIWindow *keyboardWindow in [[UIApplication sharedApplication] windows]) {
       
        // Now iterating over each subview of the available windows
        for (UIView *keyboard in [keyboardWindow subviews]) {
           
            // Check to see if the description of the view we have referenced is UIKeyboard.
            // If so then we found the keyboard view that we were looking for.
            if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES) {
                NSValue *v = [[notification userInfo] valueForKey:UIKeyboardBoundsUserInfoKey];
                CGRect kbBounds = [v CGRectValue];
               
                if(keyboardToolbar == nil) {
                    keyboardToolbar = [[UIToolbar alloc] initWithFrame:CGRectZero];
                    keyboardToolbar.barStyle = UIBarStyleBlackTranslucent;
                   
                    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(buttonClicked:)];
                    NSArray *items = [[NSArray alloc] initWithObjects:barButtonItem, nil];
                    [keyboardToolbar setItems:items];   
                    [items release];   
                }               
               
                [keyboardToolbar removeFromSuperview];
                keyboardToolbar.frame = CGRectMake(0, 0, kbBounds.size.width, 30);
                [keyboard addSubview:keyboardToolbar];
                keyboard.bounds = CGRectMake(kbBounds.origin.x, kbBounds.origin.y, kbBounds.size.width, kbBounds.size.height + 60);
               
                for(UIView* subKeyboard in [keyboard subviews]) {
                    if([[subKeyboard description] hasPrefix:@"<UIKeyboardImpl"] == YES) {
                        subKeyboard.bounds = CGRectMake(kbBounds.origin.x, kbBounds.origin.y - 30, kbBounds.size.width, kbBounds.size.height);   
                    }                       
                }
            }
        }
    }
}

// 툴바 뷰내의 닫기 버튼이 눌려졌을 때 키보드 닫기
- (void)buttonClicked:(id)sender
{   
    [diary resignFirstResponder];
}