"完成"按下时隐藏UITextView的虚拟键盘

Tai*_*mal 5 iphone uitextview iphone-sdk-3.0 ios iphone-softkeyboard

我想隐藏(resignFirstResponder)UITextView'完成'按下时的虚拟键盘.Theres没有'退出结束' UITextView.在UITextField我用' IBAction和' resignFirstResponder方法连接'退出时结束' .我怎么能这样做UITextView

小智 7

处理这种情况的正确方法是在添加完成按钮inputAccessoryViewUITextView.的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];

}
Run Code Online (Sandbox Code Playgroud)

然后通过实现您调用的操作方法来按下按钮resignFirstResponder.

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

[self.textView resignFirstResponder];

}
Run Code Online (Sandbox Code Playgroud)

这应该会导致键盘上方标准工具栏中出现一个工作"完成"按钮.


Pau*_*ulG 2

这是附件“完成”按钮的 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()
}
Run Code Online (Sandbox Code Playgroud)