2010-10-20 36 views
21

我想讓我的可編輯UITextView在用戶點擊「完成」時退出鍵盤(resignFirstResponder)。使用UITextField,我已經能夠用下面的代碼來做到這一點:如何使UITextView「完成」按鈕resignFirstResponder?

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

...然後把它在Interface Builder連接到相關UITextField到行動「真的結束上的退出。」

但是,對於UITextView,我似乎無法訪問「退出結束」操作。有關如何做到這一點的任何建議?

回答

12

新的答案

在你看來,你必須連接到IBAction爲低於UIBarButton( 「完成」):

- (IBAction)doneEditing:(id)sender { 
    [textView resignFirstResponder]; 
} 

凡TextView的是定義你的TextView出口您的.h文件並連接到Storyboard或.xib文件中。就像這樣:

@property (retain, nonatomic) IBOutlet UITextView *textView; 

老回答

檢查以下內容:

  1. 是UITextViewDelegate在.H
  2. 指定 實現委託方法 爲的UITextView: textViewShouldEndEditing,返回YES
  3. 請確保您的.m(控制器)是 代表uitextview在IB
  4. resignFirstResponder現在應該 工作。
+0

這應該起作用。在我的一些應用程序中完成了它... – gabaum10 2010-10-20 17:21:56

+2

當用戶在UITextView上按下Return/Done按鈕時,不會調用textViewShouldEndEditing,檢查shouldChangeTextInRange中的回車是唯一的方法 – valexa 2012-04-06 16:40:59

+0

錯誤的答案! 'shouldChangeTextInRange'是要走的路... – ElasticThoughts 2012-05-16 19:58:16

84

接受的答案不適用於我。相反,下面的委託方法被調用是這樣的:

- (BOOL) textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { 
    if([text isEqualToString:@"\n"]){ 
     [textView resignFirstResponder]; 
     return NO; 
    }else{ 
     return YES; 
    } 
} 

粘貼到您分配是UITextView的代表,它會工作的類。

+10

這個答案忽略了使用UITextView的所有原因,用戶需要添加多行,這是UITextView上下文中返回按鈕的作用。 – zachzurn 2012-05-03 06:21:52

+1

就是這樣做!接受的答案不起作用。 – ElasticThoughts 2012-05-16 19:57:49

+3

@zachzurn - 我不認爲這適用於這種用例,其中希望在鍵盤上有多行文本和完成按鈕。我很清楚,完成按鈕的作用就像是一個返回按鈕,而不是可用性。 – 2012-08-18 21:25:02

-4

要完成按鈕關閉鍵盤和resignFirstResponder你必須實現委託方法。

  1. 在您的.h實施UITextFieldDelegate

    @interface YourViewController : UIViewController <UITextFieldDelegate> 
    
  2. 然後實現textFieldShouldReturn在您的m

    -(BOOL) textFieldShouldReturn:(UITextField *)textField 
    { 
    [textField resignFirstResponder]; 
    return YES; 
    } 
    
  3. 不要忘記的UITextField的委託鏈接到文件的所有者(非常重要)

+0

最簡單,對我來說工作得很好。 Thanx – zxcat 2012-09-18 11:20:39

+18

然而,問題是關於UITextView,而不是UITextField ... – 2012-09-18 14:23:28

+0

upvote爲什麼? OP問UITextView,而不是UITextField ... – 2013-08-31 14:11:13

相關問題