如何在UITableViewCell中自定义配件显示图像?
-
03-07-2019 - |
题
我想在我的UITableView中使用标准显示配件图像的自定义版本。我怎样才能做到这一点?我希望对这个基本的东西不需要对UITableViewCell进行子类化。
解决方案
您需要创建自定义视图并将其分配给 UITableViewCell
对象的 accessoryView
属性。类似的东西:
myCell.accessoryView = [[ UIImageView alloc ]
initWithImage:[UIImage imageNamed:@"Something" ]];
其他提示
- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIImage *indicatorImage = [UIImage imageNamed:@"Arrow.png"];
cell.accessoryView =[[[UIImageView alloc] initWithImage:indicatorImage] autorelease];
return cell;
}
我使用上面给出的帮助代码
我遇到了与Greg相同的问题 - 附件视图没有跟踪(如果你使用UIImageView)
我解决了这个问题:UIImage * image = [ UIImage imageNamed:@"disclosure-button-grey.png" ] ;
UIControl * c = [ [ UIControl alloc ] initWithFrame:(CGRect){ CGPointZero, image.size } ] ;
c.layer.contents = (id)image.CGImage ;
[ c addTarget:self action:@selector( accessoryTapped: ) forControlEvents:UIControlEventTouchUpInside ] ;
cell.accessoryView = c ;
[ c release ] ;
有一个来自Apple的好例子显示如何使用 UIControl
来实现这种accessoryView自定义。
在UIControl中覆盖 - (void)drawRect:(CGRect)rect
并不是最简单的方法,但为您提供了很多灵活性来设置漂亮的附件视图。
我会这样做:
UIImageView *chevronImgVw = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"chevron_accessory_vw_img.png"]];
chevronImgVw.frame = CGRectMake(cell.accessoryView.frame.origin.x, cell.accessoryView.frame.origin.y, 10, 20);
cell.accessoryView = chevronImgVw;
请在投票前试试这个!因为目前它有2个upvotes和2个downvotes!
我尝试了上面的代码,它似乎不再起作用,可能是由于这篇文章的年龄,所以我会抛弃我给我定制配件视图的行。
[cell setAccessoryView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrowBtn"]]];
希望有人觉得这很有用。
注意:请勿将自定义单元格设置为标记:0。该标记是为textLabel视图保留的。如果您在Xcode Storyboard中设置了标签,则必须将自定义视图/标签的标记设置为1或更高。
注意Apple的例子:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath (NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];
UILabel *label;
label = (UILabel *)[cell viewWithTag:1];
label.text = [NSString stringWithFormat:@"%d", indexPath.row];
label = (UILabel *)[cell viewWithTag:2];
label.text = [NSString stringWithFormat:@"%d", NUMBER_OF_ROWS - indexPath.row];
return cell;
}
不隶属于 StackOverflow