2013-04-11 34 views
1

我從iOS的本地通訊錄應用程序創建一個類似於「新聯繫人」的表單。UITableViewCell與單元格中的UITextField

我發現的唯一方法是創建一個表視圖並創建一個自定義的表視圖單元格。

到目前爲止好...

現在,我的文本字段只能得到當我點擊它集中,但我想將焦點設置到TextField的,當我點擊我創建的表視圖Cell類的任何地方。

我嘗試了這一點:

- (void)setSelected:(BOOL)selected animated:(BOOL)animated 
{ 
    [super setSelected:selected animated:animated]; 
    [self.txtInputer becomeFirstResponder]; 
    // Configure the view for the selected state 
} 

但它did'nt工作,我想,焦點設置表中的最後一個字段。

回答

3

使用UITextField作爲自定義單元格作爲類中的.h(我稱之爲textField)屬性。 (我叫它TextFieldCell)

然後在didSelectRowAtIndexPath中有下面的代碼。當單擊一個單元格時,您將獲得對TextFieldCells的引用,然後您可以查找textField屬性並在其上調用becomeFirstResponder。注意我已經包含了你應該用於這個例子的枚舉。如果你不知道這些東西放在你的#includes下面,那麼把它們放到它們的下面。愛的枚舉!

//table view sections 
enum 
{ 
    TableViewSectionUsername = 0, 
    TableViewSectionPassword, 
     TableViewSectionLogin, 
    TableViewSectionCount 
}; 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    TextFieldCell *usernameCell = (TextFieldCell*)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:TableViewSectionUsername]]; 
    TextFieldCell *passwordCell = (TextFieldCell*)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:TableViewSectionPassword]]; 

    //switch section 
    switch(indexPath.section) 
    { 
     case TableViewSectionUsername: 
     { 
      [[usernameCell textField] becomeFirstResponder]; 
      break; 
     } 

     case TableViewSectionPassword: 
     { 
      [[passwordCell textField] becomeFirstResponder]; 
      break; 
     } 

     case TableViewSectionLogin: 
     { 
      if([[[usernameCell textField] text] isEqualToString:@""]) 
      { 
       NSLog(@"Please enter a username"); 
       [[usernameCell textField] becomeFirstResponder]; 
       return; 
      } 

      if([[[passwordCell textField] text] isEqualToString:@""]) 
      { 
       NSLog(@"Please enter a username"); 
       [[passwordCell textField] becomeFirstResponder]; 
       return; 
      } 

      [self dismissViewControllerAnimated:YES completion:nil]; 
      break; 
     } 

     default: 
     { 
     break; 
     } 
    } 

    //deselect table cell 
    [_tableView deselectRowAtIndexPath:indexPath animated:YES]; 

}

+0

@ user2270849我看你是新來的溢出堆棧,而且您需要命名你的問題標題的東西,更好地描述你的問題。 – 2013-04-12 15:35:59

相關問題