這只是你想達到的一般方法。
使用單個UITextView
進行輸入和輸出。
首先,爲您的UITextView
添加一個簡單字符,例如「>」,以便用戶在此字符後面開始輸入。
實現此UITextView的委託方法來聽當用戶點擊「返回」上:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if([text isEqualToString:@"\n"]) {
// Handle what happens when user presses return
return NO;
}
return YES;
}
我會做什麼這裏是當用戶按下回車鍵時,得到全UITextField
的內容和使用的東西像NSArray *stringArray = [_textField.text componentsSeparatedByString: @">"];
。這樣,數組的最後一個元素就是用戶輸入的最後一個命令。然後,測試該命令並將相應的答案附加到UITextView
。不要忘記在它後面添加@「\ n>」,以便提示用戶一個新的命令行。
剩下的事情就是防止用戶擦掉你的「>」。
這是一個想法,可能有很多其他的方式來做到這一點。評論你是否需要更多關於某事的細節!
劇透:全碼
在我的故事板,我只是有一個UITextView
掛ViewController.h,名稱爲textView
。請注意,以下代碼不會處理用戶從UITextView
中刪除文本。您可以在控制檯中輸入「hello」來測試代碼。
ViewController.m:
#import "ViewController.h"
@interface ViewController() {
// Store supported commands and outputs
NSDictionary *commands;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Initialize textView
_textView.text = @">";
[_textView becomeFirstResponder];
// Init supported commands with associated output
commands = [NSDictionary dictionaryWithObjectsAndKeys:@"Hello World !", @"hello", nil];
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
// Deleting something
if([text isEqualToString:@""]) {
UITextPosition *beginning = textView.beginningOfDocument;
UITextPosition *start = [textView positionFromPosition:beginning offset:range.location];
UITextPosition *end = [textView positionFromPosition:start offset:range.length];
UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end];
NSString *textToReplace = [textView textInRange:textRange];
NSLog(@"%@", textToReplace);
if ([textToReplace isEqualToString:@">"]) return NO;
return YES;
}
if([text isEqualToString:@"\n"]) {
// Handle what happens when user presses return
NSArray *stringArray = [_textView.text componentsSeparatedByString: @">"];
NSLog(@"Last command : %@", [stringArray lastObject]);
[self handleCommand:[stringArray lastObject]];
return NO;
}
return YES;
}
-(void)handleCommand:(NSString*)command {
NSString *output = [commands objectForKey:command];
// If an unsupported command was typed
if (output == nil) {
output = @"Unknown command";
}
// Write output to the textView
_textView.text = [_textView.text stringByAppendingString:@"\n"];
_textView.text = [_textView.text stringByAppendingString:output];
_textView.text = [_textView.text stringByAppendingString:@"\n>"];
}
這是從模擬器TextView的內容:
>hello
Hello World !
>yes
Unknown command
>
Unknown command
>hello
Hello World !
在同一時間提交。我更喜歡你的方式! – Mika
@Mikael謝謝,你的方式是我的第二選擇:] – rdurand
@objM:我添加了解決方案的完整代碼。你必須確保用戶不會刪除他不應該的東西。 – rdurand