我正在尝试更改TableView委托中的UITextField
- (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];
}
// Configure cell here
if ( indexPath.section == [self nameSectionNumber]) {
if ( indexPath.row == [self firstNameRowNumber] ){
UITextField *textFieldFromCell = [self retrieveUITextFieldFromCell:cell];
textFieldFromCell.text = [self.person firstName];
} else if ( indexPath.row == [self lastNameRowNumber] ) {
cell.textLabel.text = [self.person lastName];
}
} else if ( indexPath.section == [self emailSectionNumber] ) {
if ( indexPath.row == [self emailSectionHomeRowNumber] ) {
cell.textLabel.text = [self.person homeEmail];
} else if ( indexPath.row == [self emailSectionWorkRowNumber] ) {
cell.textLabel.text = [self.person workEmail];
}
}
return cell;
}
- (UITextField *)retrieveUITextFieldFromCell:(UITableViewCell *)cell
{
// Need to grab UITextField from cell
for (UIView *view in cell.contentView.subviews){
if ([view isKindOfClass:[UITextField class]]){
UITextField* txtField = (UITextField *)view;
return txtField;
}
}
return nil;
}
如果我不尝试修改单元格,只需执行
// Configure cell here
if ( indexPath.section == [self nameSectionNumber]) {
if ( indexPath.row == [self firstNameRowNumber] ){
cell.textLabel.text = [self.person firstName];
} else if ( indexPath.row == [self lastNameRowNumber] ) {
cell.textLabel.text = [self.person lastName];
}
}
UILabel(“名字”)消失了,UITextField消失了,这是我所期待的,因为我认为它是因为这段代码
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if ( cell == nil ) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
注意:忽略姓氏和电子邮件字段。我现在只专注于名字,以使其看起来正确。
答案 0 :(得分:0)
在我看来,您正在使用静态单元格定义表格视图。在这种情况下,您不需要为tableview实现数据源委托方法,如果这样做,您基本上会覆盖在故事板中定义的静态单元格。如果您需要为这些单元格设置内容,我建议您为单元格定义一个IBOutlet,并简单地引用该出口并直接修改文本属性。
@interface ProfileViewController ()
@property (weak, nonatomic) IBOutlet UITextField *firstNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *lastNameTextField;
@end
@implementation ProfileViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
_firstNameTextField.text = @"John";
_lastNameTextField.text = @"Smith";
}
...
@end