Objective c 要使UITextView对返回键作出反应吗

Objective c 要使UITextView对返回键作出反应吗,objective-c,xcode,Objective C,Xcode,我试图在Xcode中实现一个有点像命令行的程序。我基本上有一个UITextView,可以获取多行文本。现在,我有一个按钮,可以在用户输入命令后进行必要的更改,但我希望能够有一个方法,在用户点击UITextView中的return键后调用该方法,因此基本上它会在每个命令后进行更改。是否可以执行此操作?您可以通过为UITextView设置一个委托来执行此操作。请参阅以了解有关可以执行的操作的详细信息。注意,我没有测试过这一点,只是一个想法: - (void)textViewDidChange:(UI

我试图在Xcode中实现一个有点像命令行的程序。我基本上有一个UITextView,可以获取多行文本。现在,我有一个按钮,可以在用户输入命令后进行必要的更改,但我希望能够有一个方法,在用户点击UITextView中的return键后调用该方法,因此基本上它会在每个命令后进行更改。是否可以执行此操作?

您可以通过为
UITextView
设置一个委托来执行此操作。请参阅以了解有关可以执行的操作的详细信息。

注意,我没有测试过这一点,只是一个想法:

- (void)textViewDidChange:(UITextView *)textView
{
    if ([[textView.text substringWithRange:NSMakeRange(textView.text.length - 1, 1)] isEqualToString:@"\n"])
    { 
       [textView resignFirstResponder];
       [self methodYouWantToCall];
    }
}

如果将委托设置为实现

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
然后,您可以检查最后一个字符是否为“\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];
}

上面提到的布尔方法是一个错误的答案。。。例如,用户在文本视图更新前检查文本,以便查看旧文本。。。而且这些方法已经过时了。 按下返回键后,此用法将立即生效(当前“应答”将在按下返回键后再按下另一个键后生效):

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

@interface ViewController : UIViewController <UITextViewDelegate> {

我相信这就是你想要的答案:我敦促你改变当前选择的答案,因为它在很多情况下都是不正确的。谢谢所有的答案,伙计们。不过,我想我还是会坚持这一点。在按下返回键之后,直到按下另一个键之后,这一点才会更新。(请记住,您的函数是shouldChangeInRange,而不是didChangeInRange。
@interface ViewController : UIViewController <UITextViewDelegate> {
/* 
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.
 */