2013-07-07 4 views
0

Итак, я создаю экран входа в систему с UITableView. Существует два текстовых поля для электронной почты и пароля. Когда пользователь нажимает кнопку «Войти», я хочу сохранить содержимое этих двух текстовых полей в двух NSStrings. Как мне это сделать? Вот код для cellForRowAtIndexPath:Доступ к содержимому строки в UITableView

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *kCellIdentifier = @"Cell"; 

    UITextField *tf = [[UITextField alloc] init]; 

    UITableViewCell *cell = [self.tView dequeueReusableCellWithIdentifier:kCellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
             reuseIdentifier:kCellIdentifier]; 
     cell.accessoryType = UITableViewCellAccessoryNone; 

     if ([indexPath section] == 0) { 
      UITextField *playerTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 250, 30)]; 
      playerTextField.adjustsFontSizeToFitWidth = YES; 
      playerTextField.textColor = [UIColor blackColor]; 
      if ([indexPath row] == 0) { 
       playerTextField.placeholder = @"Email"; 
       playerTextField.keyboardType = UIKeyboardTypeEmailAddress; 
       playerTextField.returnKeyType = UIReturnKeyNext; 

       tf = jidField = [self makeTextField:@"" placeholder:playerTextField.placeholder]; 
       [cell addSubview:jidField]; 

      } 
      else { 
       playerTextField.placeholder = @"Password"; 
       playerTextField.keyboardType = UIKeyboardTypeDefault; 
       playerTextField.returnKeyType = UIReturnKeyDone; 
       playerTextField.secureTextEntry = YES; 

      } 
      //playerTextField.backgroundColor = [UIColor whiteColor]; 
      playerTextField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support 
      playerTextField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support 
      playerTextField.textAlignment = NSTextAlignmentLeft; 
      // playerTextField.tag = 0; 
      //playerTextField.delegate = self; 

      playerTextField.clearButtonMode = YES; // no clear 'x' button to the right 
      [playerTextField setEnabled: YES]; 

      [cell addSubview:playerTextField]; 

     } 

    } 

    return cell;  
} 
+4

Почему бы не подключить эти два текстовых поля с выходами и иметь прямой доступ, и, я думаю, у вас есть только эти две ячейки в таблице, если да, я также предлагаю использовать статический UITable. – null

+0

Если одна из причин использования UItableView - прокрутка, я предлагаю вам использовать UIScrollView и назначить свои текстовые поля свойствам на вашем контроллере. У UITextFields есть свойства, которые также позволяют изменять их внешний вид. –

ответ

0

В cellForRowAtIndexPath, установите тег для идентификатора пользователя и пароля поля и извлекать текстовые поля с идентификатором тега. Ниже вы найдете метод loginAction.

- (void)loginAction:(id)sender { 
    NSIndexPath *userIdRow = [NSIndexPath indexPathForRow:0 inSection:0]; 
    NSIndexPath *passwordFieldRow = [NSIndexPath indexPathForRow:1 inSection:0]; 

    UITableViewCell *userIdTableCell = (UITableViewCell *)[tableview cellForRowAtIndexPath:userIdRow]; 
    UITableViewCell *passwordFieldTableCell = (UITableViewCell *)[tableview cellForRowAtIndexPath:userIdRow]; 

    UITextField *userIDField = (UITextField *)[userIdTableCell viewWithTag:1001]; 
    UITextField *passwordField = (UITextField *)[passwordFieldTableCell viewWithTag:1002]; 

    // You can store now text to either your instance variables or properties in the following statements 
    NSLog(@"%@", userIDField.text]; 
    NSLog(@"%@", passwordField.text]; 
} 

В cellForRowAtIndexPath, вы должны пометить ваше: текстовые поля

if ([indexPath row] == 0) { 
    playerTextField.tag = 1001; 
} else { 
    playerTextField.tag = 1002; 
} 
0

Так же, как сказал Тарик, это то, как вы это делаете.

В вашем * .h файле

@interface v1ViewController : UITableViewController 
{ 

    UITextField IBOutlet *playerEmailTxt; 
    UITextField IBOutlet *playerPassword; 

} 


@property (nonatomic, retain) UITextField IBOutlet *playerEmailTxt; 
@property (nonatomic, retain) UITextField IBOutlet *playerPassword; 

В вашем * .m файл

... 
    @synthesize playerEmailTxt; 
    @synthesize playerPassword; 

    ... 
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

     static NSString *kCellIdentifier = @"Cell"; 

     UITableViewCell *cell = [self.tView dequeueReusableCellWithIdentifier:kCellIdentifier]; 
     if (cell == nil) 
    { 
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
              reuseIdentifier:kCellIdentifier]; 
      cell.accessoryType = UITableViewCellAccessoryNone; 

     if (indexPath.section == 1) 
     { 

      if (indexPath.row == 0) 
      { 
       playerEmailTxt = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 250, 30)]; 
       playerEmailTxt.adjustsFontSizeToFitWidth = YES; 
       playerEmailTxt.textColor = [UIColor blackColor]; 

        playerEmailTxt.placeholder = @"Email"; 
        playerEmailTxt.keyboardType = UIKeyboardTypeEmailAddress; 
        playerEmailTxt.returnKeyType = UIReturnKeyNext; 


        [cell addSubview:playerEmailTxt]; 

     } 
     else if (indexPath.row == 1) 
     { 

       playerPassword = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 250, 30)]; 
       playerPassword.adjustsFontSizeToFitWidth = YES; 
       playerPassword.textColor = [UIColor blackColor]; 

        playerPassword.placeholder = @"Password"; 
        playerPassword.keyboardType = UIKeyboardTypeDefault; 
        playerPassword.returnKeyType = UIReturnKeyDone; 
        playerPassword.secureTextEntry = YES; 
        [cell addSubview:playerPassword]; 

      } 

     } 

     return cell;  
    } 

Теперь добавьте ваш Войти действие

-(IBAction)LoginAction 
{ 
    NSMutableString *usrEmailStr = [NSMutableString stringWithFormat:@"%@", playerEmailTxt]; 
    NSMutableString *usrPasswdStr = [NSMutableString stringWithFormat:@"%@", playerPassword]; 

//Do whatever you want with these strings 

} 
0

Я также рекомендую вам проверить бесплатную платформу Sensible TableView. Похоже, что это идеально подходит для того, что вы пытаетесь сделать, поскольку инфраструктура автоматически загрузит данные из ваших полей и сохранит их в любой структуре данных, которую вы хотите.

Смежные вопросы