Set own cell accessory type

11,376

Solution 1

Try this:

// first create UIImageView
var imageView : UIImageView
imageView  = UIImageView(frame:CGRectMake(20, 20, 100, 320))
imageView.image = UIImage(named:"image.jpg")

// then set it as cellAccessoryType
cell.accessoryView = imageView

PS: I strongly advise you to upgrade to XCode 6.3.2 and using iOS 8.3 SDK

Solution 2

I assume you would like to get tap on accessory view, so I provide this answer with button. If not, use shargath's answer with imageView.

var saveButton = UIButton.buttonWithType(.Custom) as UIButton
        saveButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        saveButton.addTarget(self, action: "accessoryButtonTapped:", forControlEvents: .TouchUpInside)
        saveButton.setImage(UIImage(named: "check-circle"), forState: .Normal)
        cell.accessoryView = saveButton as UIView

func accessoryButtonTapped(sender:UIButton) {

}

Solution 3

Swift 5 version of Shmidt's answer, plus using sender.tag to keep track of which row the button was clicked on:

override func tableView(_ tableView: UITableView, 
    cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", 
        for: indexPath)
    let checkButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
    checkButton.addTarget(self, action:#selector(YOUR_CLASS_NAME.checkTapped(_:)), 
        for: .touchUpInside)
    checkButton.setImage(UIImage(named: "check"), for: .normal)
    checkButton.tag = indexPath.row
    cell.accessoryView = checkButton
    return cell
}


@objc func checkTapped(_ sender: UIButton) {
    print(sender.tag)
}

Solution 4

Swift 5 version, adding contentMode:

    let imageView: UIImageView = UIImageView(frame:CGRect(x: 0, y: 0, width: 20, height: 20))
    imageView.image = UIImage(named:Imge.Card.Link.download)
    imageView.contentMode = .scaleAspectFit
    cell.accessoryView = imageView
Share:
11,376
Vpor
Author by

Vpor

Updated on June 13, 2022

Comments

  • Vpor
    Vpor almost 2 years

    I'd like to set my own cellAccessoryType (an image) in an UITableViewCell. Do you know how I can do this? I'm using Swift, Xcode 6.2 and iOS 8.2. Thank you for you help!