How can I customize the accessory disclosure image in a UITableViewCell?

Viewed 45397

I would like to use a custom version of the standard disclosure accessory image in my UITableView. How can I do this? I'm hoping that sub-classing UITableViewCell is not necessary for something this basic.

9 Answers

You'll need to create a custom view and assign it to the accessoryView property of the UITableViewCell object. Something like:

myCell.accessoryView = [[ UIImageView alloc ] 
                       initWithImage:[UIImage imageNamed:@"Something" ]];

I ran into the same problem as Greg--the accessory view doesn't track (if you use an UIImageView)

I solved it like this:

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 ] ;

Swift 4 & 5:

This worked for me:

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...
}

Best of all, this lets me use tableView(_:accessoryButtonTappedForRowWith:) to handle the button actions.

I used this for the button, but the same technique works for the disclosure image, [since/so long as] there is only one class in that branch of the hierarchy tree of the element you want to touch.


Oh, right, my code calls this:

extension UIView {
    var allSubviews: [UIView] {
        return subviews.flatMap { [$0] + $0.allSubviews }
    }
}

In swift 4 & 5

myCell.accessoryView = UIImageView(image: UIImage(named: "Something"))
Related