2011-03-03 99 views
4

當'完成'按下時,我想隱藏(resignFirstResponderUITextView的虛擬鍵盤。在UITextView的Theres沒有'退出結束'。在UITextField我連接了'出口退出'與IBAction並呼籲resignFirstResponder方法。我如何用UITextView來做到這一點?'完成'按下時隱藏UITextView的虛擬鍵盤

回答

2

這裏是「完成」的配件的雨燕版按鈕:

@IBOutlet weak var textView: UITextView! 

// In viewDidLoad() 

    let toolbar = UIToolbar() 
    toolbar.bounds = CGRectMake(0, 0, 320, 50) 
    toolbar.sizeToFit() 
    toolbar.barStyle = UIBarStyle.Default 
    toolbar.items = [ 
     UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil), 
     UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: nil, action: "handleDone:") 
    ] 

    self.textView.inputAccessoryView = toolbar 

// ----------------- 

func handleDone(sender:UIButton) { 
    self.textView.resignFirstResponder() 
} 
4

我假設通過「完成」按鈕您的意思是返回鍵。這不像你想象的那麼直觀。 This question覆蓋得很好。

3

,如果你希望能夠使用您的返回鍵 [[self view] endEditing: YES];

+0

我喜歡這個解決方案。在Xamarin.IOS中相當於 View.EndEditing(true); – 2015-10-15 13:56:56

7

來處理這是在inputAccessoryView添加完成按鈕到UITextView正確的方法,你可以添加這一個動作。 inputAccessoryView是有時出現在鍵盤上方的條形。

爲了實現inputAccessoryView只需添加此方法(或其變體)並在viewDidLoad中調用它。

- (void)addInputAccessoryViewForTextView:(UITextView *)textView{ 

//Create the toolbar for the inputAccessoryView 
UIToolbar* toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)]; 
[toolbar sizeToFit]; 
toolbar.barStyle = UIBarStyleBlackTranslucent; 

//Add the done button and set its target:action: to call the method returnTextView: 
toolbar.items = [NSArray arrayWithObjects:[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], 
         [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(returnTextView:)], 
         nil]; 

//Set the inputAccessoryView 
[textView setInputAccessoryView:toolbar]; 

} 

然後按下按鈕,執行您調用的操作方法resignFirstResponder

- (void) returnBreakdown:(UIButton *)sender{ 

[self.textView resignFirstResponder]; 

} 

這應該會導致在鍵盤上方的標準工具欄中出現工作「完成」按鈕。

3

確保您聲明支持UITextViewDelegate協議。

@interface ...ViewController : UIViewController`in .h file。

在.m文件,實現以下方法

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