[英]Hide Virtual Keyboard of UITextView when 'Done' Presses
當'完成'按下時,我想隱藏( resignFirstResponder
) UITextView
的虛擬鍵盤。 在UITextView
沒有'退出時結束'。 在UITextField
我將'退出時結束'與IBAction
並調用resignFirstResponder
方法。 我怎么能用UITextView
做到這一點?
處理此問題的正確方法是在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];
}
這應該會導致鍵盤上方標准工具欄中出現一個工作“完成”按鈕。
我假設通過“完成”按鈕表示返回鍵。 它並不像你想象的那么直觀。 這個問題很好地涵蓋了它。
如果你想能夠使用你的返回鍵[[self view] endEditing: YES];
你可以將它添加到一個動作中[[self view] endEditing: YES];
確保聲明對UITextViewDelegate
協議的支持。
@interface ...ViewController : UIViewController
在.h文件中。
在.m文件中,實現以下方法
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if([text isEqualToString:@"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES; }
這是配件“完成”按鈕的Swift版本:
@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()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.