我認爲更好的方式來做到這一點是執行像textViewDidChange:
的UITextViewDelegate協議的方法。例如,你可以這樣做:
- (void)textViewDidChange:(UITextView *)textView {
NSString *currentText = [textview text];
NSArray *currentItems = [currentText componenetsSeparatedByString:@" "];
float result = 0.0;
//If a valid expression is in the text view
if([currentItems count] > 2) {
float num1 = [[currentItems objectAtIndex:0] floatValue];
float num2 = [[currentItems objectAtIndex:2] floatValue];
NSString *operator = [currentItems objectAtIndex:1];
if([operator isEqualToString:@"+"]) {
result = num1 + num2;
answerTextField.text = [NSString stringWithFormat:@"%f", result];
}
else if([operator isEqualToString:@"-"]) {
result = num1 - num2;
answerTextField.text = [NSString stringWithFormat:@"%f", result];
}
else if([operator isEqualToString:@"*"]) {
result = num1 * num2;
answerTextField.text = [NSString stringWithFormat:@"%f", result];
}
else if([operator isEqualToString:@"/"]) {
result = num1/num2;
answerTextField.text = [NSString stringWithFormat:@"%f", result];
}
else{
answerTextField.text = @"Invalid Operation";
}
}
}
這將在用戶每次在文本視圖中編輯文本時調用。它應該可以工作,但我沒有對它進行測試。確保在任何文件,這個代碼是在標題,你這樣做:
@interface yourClassName : yourSuperclass <UITextViewDelegate> {
//Your instance variables
}
//Your method and property declarations
編輯:
比方說,我把- (void)textViewDidChange:(UITextView *)textView
代碼在一個名爲MyClass.m文件。然後將文件MyClass.m應該是這樣的:
@implementation MyClass
- (void)textViewDidChange:(UITextView *)textView {
//All the above code goes here
}
- (void)viewDidLoad
{
[super viewDidLoad];
//INCLUDE THESE LINES
Sum_TextField.delegate = self;
Answer_TextField.delegate = self;
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
@end
在頭文件(MyClass.h),我會把這樣的:
@interface MyClass : UIViewController <UITextViewDelegate>
//Note: you don't declare - (void)textViewDidChange:(UITextView *)textView in the header file because you are implementing
//a protocol method.
//MAKE SURE SUM_TEXTFIELD AND ANSWER_TEXTFIELD ARE UITEXTVIEWS NOT UITEXTFIELDS
@property (strong, nonatomic) IBOutlet UITextView *Sum_TextField;
@property (strong, nonatomic) IBOutlet UITextView *Answer_TextField;
@end
希望這有助於!
好的,我對Objective-C一無所知,所以我懷疑我可以幫助解決您的問題。但是我會在這裏提出問題來幫助你:C和C++是不同的語言,所以你不應該用兩者來標記你的問題。但是這個問題實際上是關於*另一種不同的語言*:Objective-C。我這次爲你解決了標籤問題。歡迎來到Stack Overflow。 – 2012-07-25 04:38:21