わかりました、あなたがやろうとしていることを理解しました。重要なのは、セルにコントロールを追加し続け、進行中に幅を計算することだと思います。
まず、セルの内容を保持するためのデータ構造を提案します。単純な配列がその役割を果たします。私は通常、このようなことをivarとして行います。
@interface LabelWithImagesViewController ()
{
NSMutableArray *_cells;
}
@end
次に、この配列に必要なテキストと画像を入力します。私は単一の行を実行していますが、必要なすべての行に対して繰り返すことができます。
- (void)viewDidLoad
{
[super viewDidLoad];
_cells = [[NSMutableArray alloc] init];
[_cells addObject:[[NSArray alloc] initWithObjects:
[UIImage imageNamed:@"triangle.png"],
@"CAT",
[UIImage imageNamed:@"semiequal.png"],
[UIImage imageNamed:@"triangle.png"],
@"DOG",
@" If",
[UIImage imageNamed:@"triangle1.png"],
@"then",
[UIImage imageNamed:@"triangle2.png"],
nil]];
}
次に、セルを作成する必要があります。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return _cells.count;
}
#define kEquationTag 100
#define kCellHeight 44
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"equationCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIView *equationContainer;
if (cell == nil)
{
// if we don't have a cell create it, including the frame to hold our custom stuff
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
equationContainer = [[UIView alloc] initWithFrame:cell.contentView.bounds];
equationContainer.tag = kEquationTag;
[cell.contentView addSubview:equationContainer];
}
else
{
// if we are dequeing one that already exists, let's get rid of the old custom stuff
equationContainer = [cell.contentView viewWithTag:kEquationTag];
for (UIView *view in equationContainer.subviews)
{
[view removeFromSuperview];
}
}
// Configure the cell...
NSArray *cellContents = [_cells objectAtIndex:indexPath.row];
NSUInteger x = 0;
UIFont *font = [UIFont systemFontOfSize:12.0];
for (NSObject *obj in cellContents)
{
if ([obj isKindOfClass:[NSString class]])
{
NSString *text = (NSString *)obj;
CGSize size = [text sizeWithFont:font];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, (kCellHeight - size.height)/2.0, size.width, size.height)];
label.text = text;
label.font = font;
[equationContainer addSubview:label];
x += size.width;
}
else if ([obj isKindOfClass:[UIImage class]])
{
UIImage *image = (UIImage *)obj;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, (kCellHeight - image.size.height) / 2.0, image.size.width, image.size.height)];
imageView.image = image;
[equationContainer addSubview:imageView];
x += image.size.width;
}
}
return cell;
}
これにより、次のようになります。