以防萬一任何人遇到此問題,這是如何將UITextFields添加到組表。
在的UITableViewController(我假設是表的委託&數據源)實現以下功能:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
if (indexPath.section == 0) {
// Add a UITextField
UITextField *textField = [[UITextField alloc] init];
// Set a unique tag on each text field
textField.tag = titleTag2 + indexPath.row;
// Add general UITextAttributes if necessary
textField.enablesReturnKeyAutomatically = YES;
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
[cell.contentView addSubview:textField];
[textField release];
}
}
// Configure the cell...
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)configureCell:(UITableViewCell *)theCell atIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
// Get the text field using the tag
UITextField *textField = (UITextField *)[theCell.contentView viewWithTag:titleTag2+indexPath.row];
// Position the text field within the cell bounds
CGRect cellBounds = theCell.bounds;
CGFloat textFieldBorder = 10.f;
// Don't align the field exactly in the vertical middle, as the text
// is not actually in the middle of the field.
CGRect aRect = CGRectMake(textFieldBorder, 9.f, CGRectGetWidth(cellBounds)-(2*textFieldBorder), 31.f);
textField.frame = aRect;
// Configure UITextAttributes for each field
if(indexPath.row == 0) {
textField.placeholder = @"Name";
textField.returnKeyType = UIReturnKeyNext;
textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
} else if(indexPath.row == 1) {
textField.placeholder = @"Email Address";
textField.returnKeyType = UIReturnKeyNext;
textField.keyboardType = UIKeyboardTypeEmailAddress;
} else {
textField.placeholder = @"Password";
textField.returnKeyType = UIReturnKeyDone;
textField.secureTextEntry = YES;
}
}
}
很顯然,你仍然需要實現UITextFieldDelegate方法實際處理文本輸入和移動領域之間的第一響應者。
更新:自發布以來,我意識到您可以使用UIControl contentVerticalAlignment屬性,並將其設置爲UIControlContentVerticalAlignmentCenter,在這種情況下,您可以將您的框架設置爲單元格內容視圖的邊界。
我面臨着同樣的問題...這段代碼不適用於我的邏輯 – Siva 2013-10-25 13:39:09