我想在我的 UITableView 中使用标准披露附件图像的自定义版本。我怎样才能做到这一点?我希望子类 UITableViewCell 对于这个基本的东西不是必需的。
9 回答
您需要创建一个自定义视图并将其分配给对象的accessoryView
属性UITableViewCell
。就像是:
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 ] ;
我会这样做:
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 个赞成票和 2 个反对票!
Apple提供了一个很好的示例,展示了如何使用UIControl
来实现这种附件视图自定义。
- (void)drawRect:(CGRect)rect
在 UIControl 中覆盖并不是最简单的方法,但它为您提供了很大的灵活性来设计漂亮的附件视图。
斯威夫特 4 和 5:
这对我有用:
class MyCell: UITableViewCell {
// boilerplate...
fileprivate func commonInit() {
// This is the button we want, just need to change the image.
accessoryType = .detailButton
}
open override func layoutSubviews() {
super.layoutSubviews()
// Grab the "detail" button to change its icon. Functionality is set in the delegate.
if let submitButton = allSubviews.compactMap({ $0 as? UIButton }).first {
submitButton.setImage(#imageLiteral(resourceName: "icons8-enter-1"), for: .normal)
}
}
// everything else...
}
最重要的是,这让我可以使用tableView(_:accessoryButtonTappedForRowWith:)来处理按钮操作。
我将它用于按钮,但相同的技术适用于显示图像,[因为/只要]在您要触摸的元素的层次结构树的该分支中只有一个类。
哦,对了,我的代码是这样的:
extension UIView {
var allSubviews: [UIView] {
return subviews.flatMap { [$0] + $0.allSubviews }
}
}
在迅速 4 & 5
myCell.accessoryView = UIImageView(image: UIImage(named: "Something"))
注意:不要将自定义单元格设置为 tag:0。该标签是为 textLabel 视图保留的。如果您在 Xcode Storyboard 中设置标签,则必须将自定义视图/标签的标签设置为 1 或更高。
注意苹果的例子:
- (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;
}
我尝试了上面的代码,但它似乎不再工作了,可能是由于这篇文章的年龄,所以我将放弃我的行,它给了我定制的附件视图。
[cell setAccessoryView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrowBtn"]]];
希望有人觉得这很有用。