tableViewにtextFieldsが必要でした。そこで、ストーリーボードのtableViewに手動で挿入し、個々のプロパティを変更しました。しかし、プログラムを実行したときにテキストフィールドが表示されませんでした。スイッチを使って同じ手順を繰り返しました。しかし、それでも実行されませんでした。そのため、ストーリーボードにオブジェクトが存在するにもかかわらず、オブジェクトが表示されていないことがわかりました。
Q1。なぜこれが当てはまるのか、何か考えはありますか?
この問題を解決するために、これらのオブジェクトをプログラムで挿入しました。UISwitchの場合、cellForRowAtindexPath
直後に次のコードを追加しましたinitWithStyle:style reuseIdentifier:reuseIdentifier
。
UISwitch *newSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(25, 55, 77, 27)];
[newSwitch addTarget: self action: @selector(pictureSwitchAction:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:newSwitch];
これは正常に機能します。pictureSwitchAction
メソッドは期待どおりに呼び出されます。
ただし、UITextFieldで同様のことを行おうとすると、アプリがクラッシュします。(FYI ...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;
}