【问题标题】:Store values from UITextFields in NSArray programmatically iOS以编程方式将来自 UITextFields 的值存储在 NSArray iOS
【发布时间】:2014-10-01 13:41:53
【问题描述】:

首先我想说我对 iOS 编程还很陌生,所以请原谅我的无知。

我的 CustomLayout 中有三个 UITextField。我要求用户填写他们的姓名、年龄和性别。如果可能的话,我想要两件事。首先,我想,一旦用户从键盘点击返回按钮,输入字符串就会存储在 NSArray 中。此外,次要目标是在用户点击同一个按钮时遍历 UITextFields。

// CustomLayout.h
@interface CustomLayout : UIView {

UITextField *nameField;
UITextField *ageField;
UITextField *sexField;

UILabel *nameLabel;
UILabel *ageLabel;
UILabel *sexLabel;

UIButton *startButton;

}

@property (nonatomic, strong) UITextField *nameField;
@property (nonatomic, strong) UITextField *ageField;
@property (nonatomic, strong) UITextField *sexField;

@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *ageLabel;
@property (nonatomic, strong) UILabel *sexLabel;

@property (nonatomic, strong) UIButton *startButton;

-(void)textFieldShouldReturn:(UITextField*)textField;

@end

在实现文件中

//CustomLayout.m
@implementation CustomLayout

@synthesize nameField, ageField, sexField;
@synthesize nameLabel, ageLabel, sexLabel;
@synthesize startButton;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setBackgroundColor:[tkStyle viewBackgroundColor]];

        NSString *startButtonLabel = @"Start Experiment";

        //alocate and position views
        CGRect viewRect;//placeholder rect, reused for each view

        //nameLabel and nameField
        nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(120, 95, 150, 40)];
        nameLabel.textColor = [UIColor colorWithRed:106/256.0 green:180/256.0 blue:150/256.0 alpha:1.0];
        nameLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:25];
        nameLabel.backgroundColor=[tkStyle viewBackgroundColor];
        nameLabel.text=@"Enter Name:";

        nameField = [[UITextField alloc] initWithFrame:CGRectMake(280, 90, 200, 40)];
        nameField.textColor = [UIColor colorWithRed:0/256.0 green:84/256.0 blue:129/256.0 alpha:1.0];
        nameField.font = [UIFont fontWithName:@"Helvetica-Bold" size:25];
        nameField.borderStyle = UITextBorderStyleRoundedRect;
        nameField.backgroundColor=[tkStyle viewBackgroundColor];
        textFieldShouldReturn:nameField.text;

// same for ageField and sexField

        //startButton
    viewRect = CGRectMake(250, sexField.frame.origin.y+75, 200, 40);
    startButton = [[UIButton alloc] initWithFrame:viewRect];
    [startButton setTitle:startButtonLabel forState:UIControlStateNormal];
    [startButton setTitleEdgeInsets:UIEdgeInsetsMake(4, 0, 0, 0)];
    [startButton setButtonIsActive:true];
    //[startButton setOSCAddress:OSCStopPressedString];
    [startButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchDown];

    //and so on adjust your view size according to your needs
    [self addSubview:nameField];
    [self addSubview:ageField];
    [self addSubview:sexField];
    [self addSubview:nameLabel];
    [self addSubview:ageLabel];
    [self addSubview:sexLabel];
    [self addSubview:startButton];
}
return self;
}

// that should allow for users to hit 'return' button to move through textfields
-(void)textFieldShouldReturn:(UITextField*)textField;
{
    //[(NSArray *) userInfoArray addObject:textField.text];
}

// that should change Views as soon as the user presses 'Start Experiment'
-(void)buttonAction:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"startTest" object:self];
}

@end

任何帮助将不胜感激。

【问题讨论】:

    标签: ios objective-c ipad uitextfield


    【解决方案1】:

    NSDictionary 将是一个很好的方法。您可以为每个文本字段值设置唯一键。

    【讨论】:

      【解决方案2】:
      -(void)textFieldShouldReturn:(UITextField*)textField;
      

      应该是:

      - (BOOL)textFieldShouldReturn:(UITextField*)textField;
      

      另外,不要忘记返回 TRUE 或 FALSE(或 YES 或 NO)。

      要完成这项工作,请在您的类中实现 UITextFieldDelegate 协议。

      将以下代码行放入您的 .m 文件中,位于 @implementation 上方:

      @interface CustomLayout () <UITextFieldDelegate>
      @end
      

      然后,在您的 UITextFields 中设置委托:

      nameField.delegate = self;
      ageField.delegate = self;
      sexField.delegate = self;
      

      这样,textFieldShouldReturn: 方法会在用户按下 'enter' 时被调用

      【讨论】:

        【解决方案3】:

        有几点:

        1. 鉴于您的委托方法,我假设您实际上已将三个 UITextField 控件的 delegate 指定为您已在其中实现这些不同委托方法的对象。

          李>
        2. 如果要控制返回键的行为,实现textFieldShouldReturn方法:

          - (BOOL)textFieldShouldReturn:(UITextField *)textField
          {
              if (textField == self.nameField) {
                  [self.ageField becomeFirstResponder];
              } else if (textField == self.ageField) {
                  [self.sexField becomeFirstResponder];
              } else if (textField == self.sexField) {
                  [textField resignFirstResponder];
                  [self saveResults];
              }
          
              return NO;
          }
          

          我通常倾向于执行上述操作,按回车键会将我带到下一个字段,然后在最后一个字段上按回车键会关闭键盘并尝试保存结果。

          顺便说一句,在 IB 中,我会确保前两个控件的“返回键”设置为“下一步”,而最后一个控件的“返回键”设置为“开始”或“完成”。

        3. 您的保存例程将简单地用三个控件的内容填充一个对象:

          - (void)saveResults
          {
              Person *person = [[Person alloc] init];
          
              person.name = self.nameField.text;
              if (self.ageField.text) {
                  person.age = @([self.ageField.text integerValue]);
              }
              person.sex = self.sexField.text;
          
              // now do whatever you want with this object
          }
          

          这显然假设你有一个Person 类:

          @interface Person : NSObject
          @property (nonatomic, copy)   NSString *name;
          @property (nonatomic, strong) NSNumber *age;
          @property (nonatomic, copy)   NSString *sex;
          @end
          
          @implementation Person
          @end
          

          如果您更愿意使用NSDictionaryNSArray,那也可以(请确保您检查文本字段不是nil),但我个人更喜欢定义明确的模型对象,例如以上。

        4. 作为改进,您可能希望确保只输入年龄的数字值(如果您希望这样存储年龄):

          - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
          {
              if (textField == self.ageField) {
                  NSCharacterSet *invalid = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890"] invertedSet];
                  NSRange range = [string rangeOfCharacterFromSet:invalid];
                  return range.location == NSNotFound; // if non-numeric character not found, return true
              }
              return YES;
          }
          

        【讨论】:

        • 谢谢大家的回答!不幸的是,由于缺乏声誉,我无法投票赞成您的答案! @Rob,不过是一个问题。为了调用 textFieldShouldReturn,语法为 [nameField textFieldShouldReturn:YES]; ?
        • 不,你不叫它。当用户在文本字段中点击返回键时,操作系统会为您调用它(假设您已经为文本字段设置了委托属性,无论是在 IB 中还是以编程方式)。
        • @tk1863 请注意,该方法采用BOOL 返回,而不是原始问题的代码示例中的void
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 2013-07-09
        • 2010-11-09
        • 2019-03-28
        相关资源
        最近更新 更多