【问题标题】:How to apply the button's action to a text filed if the user pressed the button before returning the keyboard the keyboard如果用户在返回键盘之前按下按钮,如何将按钮操作应用于文本字段
【发布时间】:2013-11-16 23:40:23
【问题描述】:

我正在做一个简单的计算器,它对用户在触摸按钮时输入的数字进行乘法运算。它工作正常,但如果用户在按下键盘上的完成之前按下按钮,计算器将无法工作,因为用户没有按下完成,因此不会存储任何值。那么,如果用户在按下完成之前按下按钮,我如何确保存储该值。

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

【问题讨论】:

    标签: ios uibutton uitextfield


    【解决方案1】:

    您已经确定了问题的原因:您只有在用户点击完成并使用该值时才保存该值。你怎么能解决这个问题?好吧,您可以在用户输入内容的任何时候保存该值。加载视图控制器时,为文本更改事件添加一个新操作:

    [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 中分配它。

    【讨论】:

    • 第一个解决方案是在我输入数字时使程序崩溃。
    • 第二个解决方案有效:)但是当用户然后按回车时,它给出的答案与他输入的数字相同:(而且我不能在按下按钮时让键盘消失. 因为在我的应用程序中,按钮将有 3 个乘数,所以如果我让键盘消失,用户就不能使用第二个或第三个乘数。就像用户输入一个电阻值,当他第一次按下按钮时,它会乘以 1000所以它变成了 Kohms,当他再次按下时,它将是 Mohms。
    • 那么我应该写什么代码,以便在按下按钮时用户可以按下完成而不将其设置为他输入的值并且不影响文本应该返回方法? @DrummerB
    • 感谢您的帮助 :) 非常感谢 :)
    猜你喜欢
    • 1970-01-01
    • 2016-12-31
    • 2019-04-17
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 2015-10-01
    相关资源
    最近更新 更多