programing tip

완료 버튼을 키보드에 추가하는 방법은 무엇입니까?

itbloger 2020. 12. 14. 07:55
반응형

완료 버튼을 키보드에 추가하는 방법은 무엇입니까?


최신 정보:

또한 UITextViewDelegate 대리자를 구현 한 다음 컨트롤러에서 수행해 보았습니다.

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    [textView resignFirstResponder];
    return YES;
}

또한 텍스트 뷰의 델리게이트를 self (컨트롤러 뷰 인스턴스)로 설정했습니다.

완료 버튼을 클릭해도 새 줄만 삽입됩니다.


최신 정보:

지금까지 내가 한 일. 내 뷰 컨트롤러에서 UITextFieldDelegate를 구현했습니다.

콘센트를 통해 텍스트 뷰를 뷰 컨트롤러에 연결했습니다.

그런 다음


self.myTextView.delegate = self;

과:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

하지만 완료 버튼을 클릭하면 새 줄이 추가됩니다.

그래서 내 장면에 UITextView 요소가 있고 사용자가 탭하면 키보드가 나타나 편집 할 수 있습니다.

그러나 키보드를 닫을 수 없습니다.

완료 버튼을 키보드에 추가하여 해제 할 수있는 방법은 무엇입니까?


아주 간단합니다 :)

[textField setReturnKeyType:UIReturnKeyDone];

키보드를 해제하려면 <UITextFieldDelegate>클래스 에서 프로토콜을 구현하십시오.

textfield.delegate = self;

그리고 사용

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [textField resignFirstResponder];
}

또는

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

스토리 보드로 이동하여 텍스트 필드를 선택하고 Attributes Inspector 아래에 "return key"라는 옵션이 있습니다. "Done"을 선택합니다.

그런 다음 ViewController로 이동하여 다음을 추가하십시오.

- (IBAction)dismissKeyboard:(id)sender;
{
    [textField becomeFirstResponder];
    [textField resignFirstResponder];
}

그런 다음 텍스트 필드로 돌아가서 콘센트를 클릭하고 "종료시 종료 됨"을 링크하여 dismissKeyboard 작업을 수행하십시오.


UIBarButtonItem으로 Done 버튼이있는 사용자 정의보기로 UIToolBar를 추가합니다.

이것은 모든 유형의 키보드에 완료 버튼을 추가하는 더 안전하고 깨끗한 방법입니다. UIToolBar를 생성하고 Done Button을 추가하고 UITextField 또는 UITextView의 inputAccessoryView를 설정합니다.

UIToolbar *ViewForDoneButtonOnKeyboard = [[UIToolbar alloc] init];
[ViewForDoneButtonOnKeyboard sizeToFit];
UIBarButtonItem *btnDoneOnKeyboard = [[UIBarButtonItem alloc] initWithTitle:@"Done"
                                                               style:UIBarButtonItemStyleBordered target:self
                                                              action:@selector(doneBtnFromKeyboardClicked:)];
[ViewForDoneButtonOnKeyboard setItems:[NSArray arrayWithObjects:btnDoneOnKeyboard, nil]];

myTextField.inputAccessoryView = ViewForDoneButtonOnKeyboard;

완료 버튼에 대한 IBAction

 - (IBAction)doneBtnFromKeyboardClicked:(id)sender
  {
      NSLog(@"Done Button Clicked.");

      //Hide Keyboard by endEditing or Anything you want.
      [self.view endEditing:YES];
  }

SWIFT 3

var ViewForDoneButtonOnKeyboard = UIToolbar()
ViewForDoneButtonOnKeyboard.sizeToFit()
var btnDoneOnKeyboard = UIBarButtonItem(title: "Done", style: .bordered, target: self, action: #selector(self.doneBtnFromKeyboardClicked))
ViewForDoneButtonOnKeyboard.items = [btnDoneOnKeyboard]
myTextField.inputAccessoryView = ViewForDoneButtonOnKeyboard

함수

  @IBAction func doneBtnFromKeyboardClicked (sender: Any) {
     print("Done Button Clicked.")
    //Hide Keyboard by endEditing or Anything you want.
    self.view.endEditing(true)
  }

Swift 버전 :

ViewController에서 :

textField.returnKeyType = UIReturnKeyType.Done
textField.delegate = self

ViewController 이후

extension MyViewController: UITextFieldDelegate {        
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

Set the 'Return Key' option under the text field option in the inspector for your text field. Then right click on the text field and while holding CTRL select 'Did End On Exit' and drag this into your view controllers file. This will create an IBAction method. Give the method a name and then enter the following values:

[textField becomeFirstResponder];
[textField resignFirstResponder];

Your method should look like this:

- (IBAction)methodName:(id)sender;
{
    [sender becomeFirstResponder];
    [sender resignFirstResponder];
}

Ok, so I too have been struggling with this very issue. Currently I am accessing a UITextView in a UITableViewCell (via Tags). Because I am using prototype cells I cannot use IBActions nor IBOutlets like everyone suggests. Instead, I am using;

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

This will then provide me with the text each time the user hits a button. My solution then, was to get the ascii character for new line; "/n". If that is the text that was entered, I would resign the first responder. For example;

// If the text length is 0 then the user is deleting something, so only check the ascii character if there is text to check
if (text.length != 0) {
    // Get the Ascii character
    int asciiCode = [text characterAtIndex:0];
    // If the ascii code is /n or new line, then resign first responder
    if (asciiCode == 10) {
        [alertTextView resignFirstResponder];
        [DeviceTextView resignFirstResponder];
    }
}

Not sure if anyone else will need this hacky solution but I figured I'd put it out there in case someone needs it!


This is best way to add Done Button on keyboard

textField.returnKeyType = UIReturnKeyDone;

The following is my approach, in Swift 3. When the doneBtn clicked, let it send .editingDidEndOnExit event. I use this event to handle focus problem between multiple textFields.

// My customized UITextField
class MyTextField: UITextField {

    override func awakeFromNib() {
        super.awakeFromNib()

        // Add toolBar when keyboardType in this set. 
        let set : [UIKeyboardType] = [.numberPad, .phonePad]
        if (set.contains(self.keyboardType) ) {
            self.addDoneToolbar()
        }
    }

    // Add a toolbar with a `Done` button
    func addDoneToolbar() {

        let toolbar = UIToolbar()
        let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
        let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(onToolBarDone))

        toolbar.items = [space, doneBtn]
        toolbar.sizeToFit()

        self.inputAccessoryView = toolbar
    }

    @objc func onToolBarDone() {
        // I use `editingDidEndOnExit` to simulate the `Done` behavior 
        // on the original keyboard.
        self.sendActions(for: .editingDidEndOnExit)
    }
}

In Interface Builder on the properties of the textView you can set the return button type to Done.

Then you need to check for when the Return button is pressed using

  - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

Check if the text == "/n" then dismiss the keyboard by resigning first responder on your textView.

참고URL : https://stackoverflow.com/questions/10077155/how-to-add-done-button-to-the-keyboard

반응형