在IB的库中,介绍告诉我们,当按下返回键时,UITextView的键盘将消失。但实际上返回键只能作为'\n'

我可以添加一个按钮,并使用[txtView resignFirstResponder]隐藏键盘。

但是有没有办法为键盘中的返回键添加动作,这样我就不需要添加UIButton了?


当前回答

问题问的是如何用返回键来做,但我认为这可以帮助那些想要在使用UITextView时让键盘消失的人:

private func addToolBarForTextView() {
    let textViewToolbar: UIToolbar = UIToolbar()
    textViewToolbar.barStyle = .default
    textViewToolbar.items = [
        UIBarButtonItem(title: "Cancel", style: .done,
                  target: self, action: #selector(cancelInput)),
        UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
                  target: self, action: nil),
        UIBarButtonItem(title: "Post Reply", style: .done,
                  target: self, action: #selector(doneInput))
    ]
    textViewToolbar.sizeToFit()
    yourTextView.inputAccessoryView = textViewToolbar
}

@objc func cancelInput() { print("cancel") }
@objc func doneInput() { print("done") }

override func viewDidLoad() {
    super.viewDidLoad()
    addToolBarForTextView()
}

在viewDidLoad或其他生命周期方法中调用addToolBarForTextView()。

这对我来说似乎是一个完美的解决方案。

欢呼,

穆拉特

其他回答

问题问的是如何用返回键来做,但我认为这可以帮助那些想要在使用UITextView时让键盘消失的人:

private func addToolBarForTextView() {
    let textViewToolbar: UIToolbar = UIToolbar()
    textViewToolbar.barStyle = .default
    textViewToolbar.items = [
        UIBarButtonItem(title: "Cancel", style: .done,
                  target: self, action: #selector(cancelInput)),
        UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
                  target: self, action: nil),
        UIBarButtonItem(title: "Post Reply", style: .done,
                  target: self, action: #selector(doneInput))
    ]
    textViewToolbar.sizeToFit()
    yourTextView.inputAccessoryView = textViewToolbar
}

@objc func cancelInput() { print("cancel") }
@objc func doneInput() { print("done") }

override func viewDidLoad() {
    super.viewDidLoad()
    addToolBarForTextView()
}

在viewDidLoad或其他生命周期方法中调用addToolBarForTextView()。

这对我来说似乎是一个完美的解决方案。

欢呼,

穆拉特

就像matt对samvermette的评论一样,我也不喜欢检测“\n”的想法。返回键在UITextView中是有原因的,当然是去下一行。

在我看来,最好的解决方案是模仿iPhone的消息应用程序-这是在键盘上添加工具栏(和按钮)。

我从以下博客文章中得到了代码:

http://www.iosdevnotes.com/2011/02/iphone-keyboard-toolbar/

步骤:

-添加工具栏到你的XIB文件-设置高度为460

-添加工具栏按钮项(如果尚未添加)。如果需要右对齐,还可以将灵活的工具栏按钮项添加到XIB,并移动工具栏按钮项

-创建将按钮项目链接到resignFirstResponder的动作,如下所示:

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

套:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

    CGRect frame = self.keyboardToolbar.frame;
    frame.origin.y = self.view.frame.size.height - 260.0;
    self.keyboardToolbar.frame = frame;

    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

    CGRect frame = self.keyboardToolbar.frame;
    frame.origin.y = self.view.frame.size.height;
    self.keyboardToolbar.frame = frame;

    [UIView commitAnimations];
}

我发现josebama的回答是这个帖子中最完整、最干净的答案。

下面是Swift 4的语法:

func textView(_ textView: UITextView, shouldChangeTextIn _: NSRange, replacementText text: String) -> Bool {
    let resultRange = text.rangeOfCharacter(from: CharacterSet.newlines, options: .backwards)
    if text.count == 1 && resultRange != nil {
        textView.resignFirstResponder()
        // Do any additional stuff here
        return false
    }
    return true
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField; // called from textfield (keyboard)

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text; // good tester function - thanks

我知道这已经回答了,但我真的不喜欢使用字符串字面量的换行,所以这是我所做的。

- (BOOL)textView:(UITextView *)txtView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if( [text rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]].location == NSNotFound ) {
        return YES;
    }

    [txtView resignFirstResponder];
    return NO;
}

Swift 4.0更新:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if (text as NSString).rangeOfCharacter(from: CharacterSet.newlines).location == NSNotFound {
    return true
}
txtView.resignFirstResponder()
return false
}