我认为更好的方法是实现 UITextViewDelegate 协议方法,例如textViewDidChange:
. 例如,您可以执行以下操作:
- (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
希望这可以帮助!