想让UITextView做出反应以返回密钥

Ray*_*onK 5 xcode objective-c

我正在尝试在Xcode中实现一个有点像命令行的程序.我基本上有一个UITextView,可以采取多行文本.现在,我有一个按钮,在用户输入命令后会进行必要的更改,但是我希望能够在用户点击UITextView中的返回键后调用一个方法,所以基本上它会进行更改在每个命令之后.是否有可能做到这一点?

Alb*_*haw 20

上面提到的BOOL方法是一个错误的答案......对于一个人来说,在文本视图更新之前检查文本,因此他们正在查看旧文本...此外,这些方法已经过时了.一旦按下返回键,此用法将立即起作用(当按下返回键并按下另一个键后,当前的"回答"将不起作用):

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        NSLog(@"Return pressed");
    } else {
        NSLog(@"Other pressed");
    }
    return YES;
}
Run Code Online (Sandbox Code Playgroud)

不要忘记添加UITextViewDelegate到.h文件的协议中.

@interface ViewController : UIViewController <UITextViewDelegate> {
Run Code Online (Sandbox Code Playgroud)

并设置yourTextView.delegate = self;.m文件!


/* 
note: This will also get called if a user copy-pastes just a line-break... 
 unlikely but possible. If you need to ignore pasted line-breaks for some 
 reason see here: http://stackoverflow.com/a/15933860/2057171 ... 
 Now for an unrelated-tip: If you want to accept pasted line breaks however 
 I suggest you add an "or" to the conditional statement and make it also 
 check if "text" isEqualToString @"\r" which is another form of line-break 
 not found on the iOS keyboard but it can, however, be found on a website 
 and copy-pasted into your textView.  If you want to accept pasted text 
 with a line-break at the end you will need to change the 
 "isEqualToString" code above to say "hasSuffix", this will check for 
 any string %@ with a "\n" at the end. (and again for "\r") but make 
 sure you don't call your "next" method until after `return YES;` 
 has been called and the text view has been updated, otherwise 
 you will get only the text that was there before the copy paste 
 since this is "shouldChangeTextInRange" method, not 
 "didChangeTextInRange", if you do this I suggest stripping the 
 "\n" or "\r" from the end of your final string after the copy-paste 
 was made and applied and the text was updated.
 */
Run Code Online (Sandbox Code Playgroud)


jba*_*100 7

如果您将委托设置为实现的UITextView

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
Run Code Online (Sandbox Code Playgroud)

然后,您可以检查最后一个字符是否为"\n",并通过执行操作获取自上一个命令以来输入的文本

NSArray* components = [textView.text componentsSeparatedByString:@"\n"];
if ([components count] > 0) {
    NSString* commandText = [components lastObject];
    // and optionally clear the text view and hide the keyboard...
    textView.text = @"";
    [textView resignFirstResponder];
}
Run Code Online (Sandbox Code Playgroud)