我想在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分鐘.. –