본문 바로가기

iPhone

키보드 위에 닫기 버튼 넣기



아래와 같이 키보드에 닫기 버튼을 넣으려면

    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

  

  UIBarButtonItem *barItem = [[UIBarButtonItem alloc]initWithTitle:@"닫기" style:UIBarButtonItemStyleDone target:self action:@selector(closeKeyboard)];

[toolBar setItems: [NSArray arrayWithObjects [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], barItem, nil]];

  

    if(SYSTEM_VERSION_LESS_THAN(@"7.0")){

        for (UIView* view in mSearchBar.subviews) {

            if ([view isKindOfClass:[UITextField class]]) {

                ((UITextField*)view).inputAccessoryView = toolBar;

            }

        }

    }else{

        [barItem setTintColor:[UIColor whiteColor]];

        mSearchBar.inputAccessoryView = toolBar;

    }


여기서 mSearchBar는 UITextField처럼 키보드를 띄우는 입력 창이며  resignKeyboard는 닫기명령어가 들어가 있는 메서드이다. SYSTEM_VERSION_LESS_THAN()은 버전을 체크하기 위한 defin메서드이고 7.0 미만의 버전에서는 inputAccessoryView의 프로퍼티가 직접 접근이 불가능 하기 때문에 분기처리가 필요하다.

- (void)closeKeyboard

{

    [mSearchBar resignFirstResponder];

}


만약 버튼이 더 필요할 경우는 아래와 같이 버튼을 추가하고 알맞는 이벤트를 연결해 주면 된다.

    [toolBar setItems: [NSArray arrayWithObjects:

[[UIBarButtonItem alloc]initWithTitle:@"이전" style:UIBarButtonItemStyleBordered target:self action:@selector(formerTextField)],

[[UIBarButtonItem alloc] initWithTitle:@"다음" style:UIBarButtonItemStyleBordered target:self action:@selector(nextTextField)],

[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],

[[UIBarButtonItem alloc]initWithTitle:@"확"style:UIBarButtonItemStyleDone target:self action:@selector(resignKeyboard)], nil]];