我有一个自定义UITableViewCell
类,想要线性显示图像和字符串。例如:
第1行:[Image1] string1 [Image2] string2 [Image3]
第2行:[Image4] string3 [Image5]
图像的宽度各不相同,但我想要相等的间距。我该怎么做?我试过操纵子视图和CGRectMake
无济于事。
此外,我使用NSDictionary
来保存内容,并且每个单元格的图片/字符串数量不是恒定的。
我的CustomCell
课程:
#import "CustomCell.h"
@implementation CustomCell
@synthesize primaryLabel,secondaryLabel,image1;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
// Initialization code
primaryLabel = [[UILabel alloc]init];
primaryLabel.textAlignment = UITextAlignmentLeft;
primaryLabel.font = [UIFont systemFontOfSize:16];
secondaryLabel = [[UILabel alloc]init];
secondaryLabel.textAlignment = UITextAlignmentLeft;
secondaryLabel.font = [UIFont systemFontOfSize:14];
image1 = [[UIImageView alloc]init];
[self.contentView addSubview:primaryLabel];
[self.contentView addSubview:secondaryLabel];
[self.contentView addSubview:image1];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
CGRect frame;
frame= CGRectMake(0 ,5, 200, 25);
primaryLabel.frame = frame;
frame= CGRectMake(0 ,30, 200, 25);
secondaryLabel.frame = frame;
frame= CGRectMake(0, 60, 23, 20);
image1.frame = frame;
...
我的RootViewController
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Set up the cell...
NSDictionary *dictionary = nil;
//Search
if (tableView == self.searchDisplayController.searchResultsTableView)
{
dictionary = [self.filteredListContent objectAtIndex:indexPath.row];
}
else
{
dictionary = [self.tableDataSource objectAtIndex:indexPath.row];
}
//Original
cell.primaryLabel.text = [dictionary objectForKey:@"Title"];
for (NSArray *keystroke in [dictionary objectForKey:@"Strokes"]) {
for (int i = 0; i < 2; i++) {
if ([(NSString *)keystroke isEqualToString:@"string1"] || [(NSString *)keystroke isEqualToString:@"string2"]) {
cell.secondaryLabel.text = (NSString *)keystroke;
}
else {
NSString *imageFilePath = [NSString stringWithFormat:@"%@.png", keystroke];
NSLog(@"%@", imageFilePath);
UIImage *myimage = [UIImage imageNamed:imageFilePath];
cell.image1.image = myimage;
}
}
}
return cell;
}
...
显然这里有很多漏洞。首先,当我遍历我的字典时,我需要将CustomCell
子视图向右移动,这样我就可以将图像/文本放在上一个子视图旁边。
答案 0 :(得分:0)
你走在正确的轨道上。在UITableViewCell
子类中,您需要覆盖layoutSubviews
,手动为每个CGRects
或UIImageView
定义UILabel
,并将它们设置为相应视图的框架。
结帐CGRectGetMaxX。在这种情况下它将非常有用。