画面に簡単なUITableViewを追加しました。ただし、その中のセルに一連のカスタムUI要素(主にビューとラベル)を表示する必要があります。UITableViewCellを使用すると、自由にカスタマイズする機会があまりないため、必要なすべての要素をセルのサブビューとして追加することにしました。これが私のcellForRowAtIndexPathメソッドです。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(10.0f, 10.0f, 25.0f, 25.0f)];
view1.backgroundColor = [UIColor redColor];
view1.layer.shadowColor = [[UIColor blackColor] CGColor];
view1.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
view1.layer.shadowOpacity = 0.8f;
view1.layer.shadowRadius = 3.0f;
[cell addSubview:view1];
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(85.0f, 5.0f, 100.0f, 15.0f)];
label1.text = @"dummy text 1";
label1.backgroundColor = [UIColor clearColor];
label1.textColor = [UIColor lightGrayColor];
label1.textAlignment = UITextAlignmentRight;
label1.font = [UIFont systemFontOfSize:12.0f];
label1.lineBreakMode = NSLineBreakByTruncatingTail;
label1.shadowOffset = CGSizeMake(0.0f, 1.0f);
label1.shadowColor = [UIColor blackColor];
[cell addSubview:label1];
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(85.0f, 25.0f, 100.0f, 15.0f)];
label2.text = @"dummy text 2";
label2.backgroundColor = [UIColor clearColor];
label2.textColor = [UIColor lightGrayColor];
label2.textAlignment = UITextAlignmentRight;
label2.font = [UIFont systemFontOfSize:12.0f];
label2.lineBreakMode = NSLineBreakByTruncatingTail;
label2.shadowOffset = CGSizeMake(0.0f, 1.0f);
label2.shadowColor = [UIColor blackColor];
[cell addSubview:label2];
UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(85.0f, 45.0f, 100.0f, 15.0f)];
label3.text = @"dummy text 3";
label3.backgroundColor = [UIColor clearColor];
label3.textColor = [UIColor lightGrayColor];
label3.textAlignment = UITextAlignmentRight;
label3.font = [UIFont systemFontOfSize:12.0f];
label3.lineBreakMode = NSLineBreakByTruncatingTail;
label3.shadowOffset = CGSizeMake(0.0f, 1.0f);
label3.shadowColor = [UIColor blackColor];
[cell addSubview:label3];
return cell;
}
上記のコードはすべて、セルのカスタマイズに関する限り正常に機能します。問題は、セルが表示領域を離れるときに、そのサブビューが解放されないことです。テーブルビューを上下に動かすと、追加されたUIViewの影がどんどん暗くなり、ラベルもリリースされていないと思います。
この問題を解決するにはどうすればよいですか?UITableViewCellクラスをサブクラス化できると思いますが、セルのクラス内にサブビューを追加するだけです。それは解決策ではないようです。セルが消えたときにサブビューを解放する方法や、セルを真に自由にカスタマイズするための信頼できる方法はありますか?
ありがとう!
いくつかの追加情報:IBを使用していません(プログラムですべてを実行します)ARCを使用していますXcode4.6を使用していますSDKはiOS6.1です