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!
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
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) {
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With