Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set own cell accessory type

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!

like image 962
Vpor Avatar asked May 21 '15 10:05

Vpor


3 Answers

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

like image 183
Adam Bardon Avatar answered Nov 10 '22 02:11

Adam Bardon


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) {

}
like image 37
Shmidt Avatar answered Nov 10 '22 02:11

Shmidt


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)
}
like image 31
Roman Sheydvasser Avatar answered Nov 10 '22 04:11

Roman Sheydvasser