我想在tableView中使用textField。所以我手动将它们插入到故事板的tableView中并修改它们各自的属性。但是,当我运行程序时,我看不到文本字段。我用一个开关重复了同样的过程。但它仍然没有运行。所以我认为,尽管它们出现在故事板中,但它们并没有显示出来。将UITextField插入到TableView中
Q1。任何想法为什么这是这种情况?
为了克服这个问题,我以编程方式插入这些对象。对于UISwitch,我在initWithStyle:style reuseIdentifier:reuseIdentifier
之后在cellForRowAtindexPath
后添加了以下代码。
UISwitch *newSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(25, 55, 77, 27)];
[newSwitch addTarget: self action: @selector(pictureSwitchAction:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:newSwitch];
这工作正常。按预期方式调用pictureSwitchAction
方法。
但是,当我尝试用UITextField做类似的事情时,应用程序崩溃。 (仅供参考... field0
是一个声明为property
)这里是我的代码:
field0 = [[UITextField alloc] initWithFrame:CGRectMake(0, 50, 320, 44)]; // (1)
cell = (UITableViewCell *)[field0 superview]; // (2)
[self.view addSubview:field0]; // (3)
(1)和(2)(评论(3))崩溃的应用程序。错误:*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
我的理解是,单元必须先返回,然后才能为其分配一些值。但是(1)和(3)(评论(2)),不会产生任何结果。我不知道为什么这可以用于交换机而不是UITextField。
对Q1的任何反应以及如何以编程方式插入textField?
谢谢!
编辑1
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone; // VERY IMPORTANT
if(indexPath.section == 2)
{
if (indexPath.row == 0)
{
field0 = [[UITextField alloc] initWithFrame:CGRectMake(0, 50, 320, 44)];
cell = (UITableViewCell *)[field0 superview];
// [self.view addSubview:field0];
}
if (indexPath.row == 1)
{
field1 = [[UITextField alloc] initWithFrame:CGRectMake(0, 50, 300, 43)];
cell = (UITableViewCell *)[field1 superview];
// [self.view addSubview:field1];
}
if (indexPath.row == 2)
{
field2 = [[UITextField alloc] initWithFrame:CGRectMake(0, 50, 300, 43)];
cell = (UITableViewCell *)[field2 superview];
// [self.view addSubview:field2];
}
}
return cell;
}
我怀疑你的问题是你如何把它放在一起。发布你的整个'tableView:cellForRowAtIndexPath:'方法,因为这应该阐明为什么你会得到异常。 – kamprath
当然..请检查我的编辑在2分钟.. –