1

我正在学习 obj-c 并给自己一个简单的任务,即创建一个具有 2 uitextfieldslabel&的应用程序button(按钮汇总 2 个数字并在标签中显示结果)。我制作了这个应用程序,但我还没有弄清楚如何textfields与“完成”按钮和“仅限数字”一起进行交互。

下面是我的代码:

#import UIKit/UIKit.h

@interface ViewController : UIViewController

@property IBOutlet UILabel *label;
@property IBOutlet UITextField *textField1;
@property IBOutlet UITextField *textField2;
@property NSInteger textFieldInt1, textFieldInt2;
@property NSString *textFieldStr1, *textFieldStr2;

-(IBAction)button:(id)sender;
-(IBAction)hideKeyboard:(id)sender;

@end


#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

@synthesize label, textField1, textField2, textFieldInt1, textFieldInt2, textFieldStr1, textFieldStr2;

-(IBAction)button:(id)sender {
    textFieldInt1=[textField1.text integerValue];
    textFieldInt2=[textField2.text integerValue];
    label.text=[NSString stringWithFormat: @"%d", textFieldInt1+textFieldInt2];
    [self.view endEditing:YES];
}



- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

    [self.textField1 setReturnKeyType:UIReturnKeyDone];
    [self.textField2 setReturnKeyType:UIReturnKeyDone];

}

-(IBAction)hideKeyboard:(id)sender
{
    [self.view endEditing:YES];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range     replacementString:(NSString *)string {
    if(![string intValue] && ![string isEqualToString:@""] && ![string isEqualToString:@"0"])
    {
    return NO;
    } else {
    return YES;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
    [super touchesBegan:touches withEvent:event];
}


@end

我还(在情节提要中)连接textFieldshideKeyboard (didEndOnExit)、 和button以及button (touchUpInside)所有出口(textfieldsbuttonlabel)。

问题是: numbers only输入不适用于done. 如果我使用delegate(情节提要中的新引用插座连接到两者textfields)我会numbers only输入textfieldsdone按钮不起作用(当我在 iPhone 上按下它时没有任何反应)。如果我不使用delegate我会得到all characters输入但done工作正常(当我按下它时 iPhone 键盘隐藏)。

有什么建议我可能在这里做错了吗?

4

1 回答 1

0

实现 UITextFieldDelegate 方法:

// This is how we get rid of the keyboard.
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    //Do whatever you need to to save etc...
    [textField resignFirstResponder];
    return NO;
}

这告诉键盘在按下完成按钮时隐藏。请务必将您的视图控制器设置为文本字段的委托: myTextField.delegate = self; (可能在 viewDidLoad 中)

于 2012-11-14T16:50:18.173 回答