我正在做一个简单的计算器,可以对用户触摸按钮时输入的数字进行乘法运算。它的工作正常,但是如果用户在按下键盘上的“完成”之前按下了按钮,计算器将无法工作,因为用户没有按下“完成”,因此不会存储任何值。因此,如果用户在按下完成之前先按下按钮,那么我如何确保该值被存储。
m文件的代码
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,copy) NSString* number;
@property (nonatomic) double ans;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
self.number= self.enteredValue.text;
if (textField == self.enteredValue) {
[textField resignFirstResponder];
self.ans = [self.enteredValue.text doubleValue];
self.answer.text = [NSString stringWithFormat:@"%f",self.ans];
}
NSLog(@"%f",self.ans);
return YES;
}
- (IBAction)multiplierPressed:(UIButton *)sender {
self.answer.text = [NSString stringWithFormat:@"%f",self.ans*10];
}
@end
头文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *enteredValue;
- (IBAction)multiplierPressed:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UILabel *answer;
@end
您已经确定了问题的原因:只有在用户点击“完成”并使用该值时,您才保存该值。你怎么解决呢?好了,您可以在用户键入任何内容时保存该值。加载视图控制器时,为文本更改事件添加一个新操作:
[textField addTarget:self
action:@selector(textFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];
当文本字段中的文本更改时,这将使textFieldDidChange:方法被调用。
或者,您可以停止将值保存到自己的实例变量中,而仅在用户点击x10按钮时使用文本字段中当前的值。
- (IBAction)multiplierPressed:(UIButton *)sender {
float enteredValue = [self.textField.text floatValue];
self.answer.text = [NSString stringWithFormat:@"%f", enteredValue * 10];
}
在这种情况下,您必须在视图控制器中声明一个textField属性,然后在Interface Builder中对其进行分配。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句