簡體   English   中英

將完成按鈕添加到鍵盤頂部

[英]Add a done button to the top of the keyboard

我正在制作一個具有UITextView的通用應用程序。 當應用程序在iPad上運行時,右下角有一個按鈕,可以讓我關閉鍵盤。 iPhone版沒有這樣的按鈕。 我在一些iPhone應用程序上看到鍵盤頂部有一個帶有完成選項的欄。 是否有一種簡單的方法可以將iPad風格的鍵盤按鈕添加到iPhone應用程序中。 如果沒有,將完成樣式欄添加到鍵盤頂部的最佳方法是什么? 提前致謝。

請試試這段代碼

 //set up a placeholder variable for the textfield user typing
 UITextView *currentTextView;

-(void)addDoneToolBarToKeyboard:(UITextView *)textView
{
    UIToolbar* doneToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    doneToolbar.barStyle = UIBarStyleBlackTranslucent;
    doneToolbar.items = [NSArray arrayWithObjects:
                       [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                       [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneButtonClickedDismissKeyboard)],
                       nil];
    [doneToolbar sizeToFit];
    textView.inputAccessoryView = doneToolbar;
}

 //remember to set your text view delegate
 //but if you only have 1 text view in your view controller
 //you can simply change currentTextField to the name of your text view
 //and ignore this textViewDidBeginEditing delegate method
 - (void)textViewDidBeginEditing:(UITextView *)textView
 {
     currentTextView = textView;
 }

-(void)doneButtonClickedDismissKeyboard
{
     [currentTextView resignFirstResponder];
}

並在你的視圖中添加這個加載

 [self addDoneToolBarToKeyboard:self.textView];

希望有所幫助

同樣的答案swift3

func addDoneToolBarToKeyboard(textView:UITextView)
{
    let doneToolbar : UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 50))
    doneToolbar.barStyle = UIBarStyle.default
    let flexibelSpaceItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)

    let hideKeyboardItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(self.dismissKeyboard))
    doneToolbar.items = [flexibelSpaceItem, hideKeyboardItem!]
    doneToolbar.sizeToFit()
    textView.inputAccessoryView = doneToolbar
}

和解雇功能將是:

func dismissKeyboard()
{
  self.view.endEditing(true)
}

您可以通過以下方式隨時在一行代碼中執行此操作:

[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) 
                                           to:nil 
                                         from:nil
                                     forEvent:nil];

這會將resignFirstResponder發送到響應者鏈。 當前文本視圖將是第一個響應者,因此它將獲取消息並辭職第一響應者。

我知道這是一個太遲的答案,但在iOS 8中我沒有隱藏鍵盤,我的TEXT視圖與答案之前。

僅供參考我只是添加這個。

// Para esconder el teclado al oprimir el fondo de la pantalla
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.answerTextView endEditing:YES];
}

摘自theapplady

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM