UITableViewCell的contentView中的UITextField的值獲取有幾種方法,本人簡單總結一下。
1. 獲取UITextField所以Cell的NSIndexPath,知道了NSIndexPath就知道了這個UITextField是干什么的了。
可以在
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { //get cell UITableViewCell *cell = [UITableViewCell ][[textField superview] superview]; NSIndexPath *indexPath = [tableView indexPathForCell:cell]; }
或
- (void)textFieldDidEndEditing:(UITextField *)textField { //get cell UITableViewCell *cell = (UITableViewCell *)[[textField superview] superview]; NSIndexPath *indexPath = [tableView indexPathForCell:cell]; }
中得知道UITextField中text是哪一個數據結構的值,前一個是實時的,后一個是失去焦點時一次性的。
2。第二種方法與上面第一個有點類似也是實時的,來自:http://blog.sina.com.cn/s/blog_9ca91e4a0100xlvu.html
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSInteger row = [indexPath row]; static NSString *CellIdentifier = @"CellIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; cell.selectionStyle = UITableViewCellSelectionStyleNone; } cell.textLabel.text = [_passwordArray objectAtIndex:row]; CGRect textFieldRect = CGRectMake(0.0, 0.0f, 215.0f, 31.0f); UITextField *theTextField = [[UITextField alloc] initWithFrame:textFieldRect]; theTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; theTextField.returnKeyType = UIReturnKeyDone; theTextField.secureTextEntry = YES; theTextField.clearButtonMode = YES; theTextField.tag = row; theTextField.delegate = self; //此方法為關鍵方法 [theTextField addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged]; switch (row) { case 0: theTextField.placeholder = @"請輸入舊密碼"; break; case 1: theTextField.placeholder = @"請輸入新密碼"; break; case 2: theTextField.placeholder = @"請再次輸入新密碼"; break; default: break; } cell.accessoryView = theTextField; [theTextField release]; return cell; } - (void)textFieldWithText:(UITextField *)textField { switch (textField.tag) { case 0: self.theOldPassword = textField.text; break; case 1: self.theNewPassword = textField.text; break; case 2: self.theTwiceNewPassword = textField.text; break; default: break; } }
轉自 http://blog.csdn.net/favormm/article/details/7380160