number of radio buttons in a static tableview cell in swift - ios

I have been trying to add 3 radio buttons for gender selection in a static tableviewcell.But am not able to do that.Can any one help to do this.
func setGenderCell(indexPath : IndexPath) -> UITableViewCell {
let cell : SetGenderTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "SetGenderTableViewCell", for: indexPath) as! SetGenderTableViewCell
cell.subject.text = self.profileData[indexPath.row].getName()
cell.genderImage.image = UIImage(named: self.profileData[indexPath.row].getImage())
cell.maleButton.addTarget(self, action: #selector(self.maleGenderSelect), for: .touchUpInside)
cell.femaleButton.addTarget(self, action: #selector(self.femaleGenderSelect), for: .touchUpInside)
cell.othersButton.addTarget(self, action: #selector(self.othersGenderSelect), for: .touchUpInside)
cell.maleButton.tag = 1
cell.femaleButton.tag = 2
cell.othersButton.tag = 3
return cell
}
#objc func maleGenderSelect(){
let cell : SetGenderTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "SetGenderTableViewCell", for: IndexPath) as! SetGenderTableViewCell
cell.maleRadioImage.image = UIImage(named: "")
cell.femaleRadioImage.image = UIImage(named: "")
cell.othersRadioImage.image = UIImage(named: "")
}
#objc func femaleGenderSelect(){
}
#objc func othersGenderSelect(){
}
Reference Image:

Refer this pseudo Code,
Create GenderCellDelegate
protocol GenderCellDelegate : class {
func genderSelected(_ gender : Gender)
}
Enum For gender
enum Gender : Int {
case male = 1, female, other
}
GenderTableViewCell
class GenderTableViewCell: UITableViewCell {
#IBOutlet weak var btnMale : UIButton!
#IBOutlet weak var btnFemale : UIButton!
#IBOutlet weak var btnOther : UIButton!
weak var delegate : GenderCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
// Your can do below from XIB also
// Set buttons images for selcted and normal state
btnMale.setImage(UIImage(named: "radio-on"), for: .selected)
btnFemale.setImage(UIImage(named: "radio-on"), for: .selected)
btnOther.setImage(UIImage(named: "radio-on"), for: .selected)
btnMale.setImage(UIImage(named: "radio-off"), for: .normal)
btnFemale.setImage(UIImage(named: "radio-off"), for: .normal)
btnOther.setImage(UIImage(named: "radio-off"), for: .normal)
// Optional - if required
btnMale.isSelected = true // For default selection
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#IBAction func btnMaleSelected(_ sender : UIButton) {
self.btnMale.isSelected = true
self.btnFemale.isSelected = false
self.btnOther.isSelected = false
delegate?.genderSelected(.male)
}
#IBAction func btnFemaleSelected(_ sender : UIButton) {
self.btnMale.isSelected = false
self.btnFemale.isSelected = true
self.btnOther.isSelected = false
delegate?.genderSelected(.female)
}
#IBAction func btnOtherSelected(_ sender : UIButton) {
self.btnMale.isSelected = false
self.btnFemale.isSelected = false
self.btnOther.isSelected = true
delegate?.genderSelected(.other)
}
}
Your Controller
class MyController : UIViewController , UITableViewDelegate, UITableViewDataSource, GenderCellDelegate {
:
:
func genderSelected(_ gender: Gender) {
switch gender {
case .male:
print("Male selected")
break
case .female:
print("Female selected")
break
case .other:
print("Other selected")
break
}
// reload tableview row for gender cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let genderCell = tableView.dequeueReusableCell(withIdentifier: "GenderTableViewCell") as! GenderTableViewCell
genderCell.delegate = self
return genderCell
}
}

Related

Save user settings using user default swift

I'm working on an application where users can view terms and like or dislike terms.
I'm stack on saving user settings from the table view using user default. I want to save when users click the like or dislike buttons, and when they run the app again the button stays filled
I have a table view cell that contains an outlet for the button and action
import UIKit
class TerminologistTVCell: UITableViewCell {
#IBOutlet weak var btnLike: UIButton!
#IBOutlet weak var btnDislike: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
lconfigureUI()
dconfigureUI()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func lconfigureUI(){
let thumbsdown = UIImage(systemName: "hand.thumbsdown")
let thumbsdownfilled = UIImage(systemName: "hand.thumbsdown.fill")
btnDislike.setImage(thumbsdown, for: .normal)
btnDislike.setImage(thumbsdownfilled, for: .selected)
}
func dconfigureUI(){
let thumbsup = UIImage(systemName: "hand.thumbsup")
let thumbsupfilled = UIImage(systemName: "hand.thumbsup.fill")
btnLike.setImage(thumbsup, for: .normal)
btnLike.setImage(thumbsupfilled, for: .selected)
}
#IBAction func btnLike(_ sender: UIButton) {
sender.isSelected.toggle()
if (sender.isSelected){
btnDislike.isSelected = false
}else{
btnDislike.isSelected = false
}
}
#IBAction func btnDislike(_ sender: UIButton) {
sender.isSelected.toggle()
if (sender.isSelected){
btnLike.isSelected = false
}else{
btnLike.isSelected = false
}
}}
And the ViewController to view the terms and save settings. I tried to save the setting in cellForRow it worked, but when I clicked on the button, it saved for all cells(the button is filled in all cells), not for a cell that I pressed. I want to save for pressed cell
class TerminologistVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var termaArray = MDTerms()
let termName = ""
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return termaArray.arabicTerm.count
}
let userDefaults = UserDefaults.standard
let btnLikePressed = "Likepressed"
let btnDisLikePressed = "DisLikepressed"
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TerminologistTVCell
cell.textLabel?.text = self.termaArray.arabicTerm[indexPath.row]
cell.btnLike.tag = indexPath.row
cell.btnLike.addTarget(self, action: #selector(likeTerm(sender:)), for: .touchUpInside)
cell.btnDislike.tag = indexPath.row
cell.btnDislike.addTarget(self, action: #selector(dislikeTerm(sender:)), for: .touchUpInside)
if userDefaults.bool(forKey: btnLikePressed){
cell.btnLike.isSelected = true
}else{
cell.btnLike.isSelected = false
}
if userDefaults.bool(forKey: btnDisLikePressed){
cell.btnDislike.isSelected = true
}else{
cell.btnDislike.isSelected = false
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
#objc
func likeTerm(sender: UIButton){
print("cell index = \(sender.tag)")
if sender.isSelected{
userDefaults.set(true, forKey: btnLikePressed)
}else{
userDefaults.set(false, forKey: btnLikePressed)
}
}
#objc
func dislikeTerm(sender: UIButton){
print("cell index = \(sender.tag)")
if sender.isSelected{
userDefaults.set(true, forKey: btnDisLikePressed)
}else{
userDefaults.set(false, forKey: btnDisLikePressed)
}
}
My application looks like
ViewController
You are using only two keys in UserDefault which are btnDisLikePressed and btnLikePressed, and clearly you will always get the same values for all cells with all terms. Instead use the termaArray.arabicTerm[indexPath.row] (or in your case cell.textLabel?.text) as the key in UserDefaults.

Is there a way to get the id of a UITableViewCell?

my problem: I want to open some kind of Profil if a user pushes a Button in a Table-View Cell. The Cells Data is downloaded from Parse.
The idea is based on Instagram, if you click on the username-button on Insta the profile from the user who posted the image will open. I want to create the same code, but i can't create the code to get the user. Can you help me?
Heres some code:
import UIKit
import Parse
class HomeController: UIViewController, UITableViewDelegate, UITableViewDataSource {
private let reuseIdentifer = "FeedCell"
var delegate: HomeControllerDelegate?
var newCenterController: UIViewController!
let tableView = UITableView()
//Für Parse:
var users = [String: String]()
var comments = [String]()
var usernames = [String]()
var lastnames = [String]()
var imageFiles = [PFFileObject]()
var wischen: UISwipeGestureRecognizer!
var wischen2: UISwipeGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
getData()
configureNavigationBar()
configurateTableView()
wischen = UISwipeGestureRecognizer()
wischen.addTarget(self, action: #selector(handleMenuToggle))
wischen.direction = .right
wischen.numberOfTouchesRequired = 1
view.addGestureRecognizer(wischen)
wischen2 = UISwipeGestureRecognizer()
wischen2.addTarget(self, action: #selector(handleMenuToggle))
wischen2.direction = .left
wischen2.numberOfTouchesRequired = 1
view.addGestureRecognizer(wischen2)
}
#objc func handleMenuToggle() {
delegate?.handleMenuToggle(forMenuOption: nil)
}
#objc func showProfile() {
let vc: AProfileViewController!
vc = AProfileViewController()
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true)
}
func configureNavigationBar() {
navigationController?.navigationBar.barTintColor = .darkGray
navigationController?.navigationBar.barStyle = .black
navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.font: UIFont(name: "Noteworthy", size: 22)!, NSAttributedString.Key.foregroundColor: UIColor.white]
//navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
navigationItem.title = "Mobile Job Board"
navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "ic_menu_white_3x").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(handleMenuToggle))
navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "ic_mail_outline_white_2x").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(showCreateNewArticle))
}
//MARK: Table View
//skiped table view configuration
}
// - MARK: Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifer, for: indexPath) as! FeedCell
imageFiles[indexPath.row].getDataInBackground { (data, error) in
if let imageData = data {
if let imageToDisplay = UIImage(data: imageData) {
cell.postImage.image = imageToDisplay
}
}
}
cell.descriptionLabel.text = comments[indexPath.row]
cell.userButton.setTitle("\(usernames[indexPath.row]) \(lastnames[indexPath.row])", for: UIControl.State.normal)
cell.userButton.addTarget(self, action: #selector(showProfile), for: .touchUpInside)
return cell
}
//skiped
}
Thanks a lot!
Tom
The issue here is that your button works on a selector and it has no idea about the sender or where it was called from.
I would do this by creating a custom table view cell (e.g. FeedCell) which allows you to set a delegate (e.g. FeedCellDelegate). Set your class as the delegate for the cell and pass into the cell it's current indexPath. You can then return the indexPath in the delegate call.
Example: Note that code has been removed for simplicity and this code has not been tested. This is simply to guide you in the right direction.
View Controller
import UIKit
class HomeController: UIViewController {
// stripped additional information for example
func showProfile(_ username: String) {
let vc: AProfileViewController!
vc = AProfileViewController()
vc.username = username
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true)
}
}
extension HomeController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifer, for: indexPath) as! FeedCell
cell.delegate = self
cell.descriptionLabel.text = comments[indexPath.row]
cell.userButton.setTitle("\(usernames[indexPath.row]) \(lastnames[indexPath.row])", for: UIControl.State.normal)
cell.setIndex(indexPath)
return cell
}
}
extension HomeController: FeedCellDelegate {
func didPressButton(_ indexPath: IndexPath) {
let userName = usernames[indexPath.row]
showProfile(username)
}
}
Feed Cell
import UIKit
protocol FeedCellDelegate {
didPressButton(_ indexPath: IndexPath)
}
class FeedCell: UICollectionViewCell {
var delegate: FeedCellDelegate?
var indexPath: IndexPath
#IBOutlet weak var userButton: UIButton
setIndex(_ indexPath: IndexPath) {
self.indexPath = indexPath
}
#IBAction userButtonPressed() {
if(delegate != nil) {
delegate?.didPressButton(indexPath)
}
}
}
You can generically and in a type safe way get the parent responder of any responder with:
extension UIResponder {
func firstParent<T: UIResponder>(ofType type: T.Type ) -> T? {
return next as? T ?? next.flatMap { $0.firstParent(ofType: type) }
}
}
So:
Get the parent tableviewCell of your button in the target action function
Ask your tableview for the index path
Use the index path.row to index into your users array:
#objc func showProfile(_ sender: UIButton) {
guard let cell = firstParent(ofType: UITableViewCell.self),
let indexPath = tableView.indexPath(for: cell) else {
return
}
let user = users[indexPath.row]
... do other stuff here ...
}

Adding a target to UIButton in UITableViewCell with didSet

I am trying to refactor my code and I can't seem to active the handleFavoriteStar() action from the SearchController when the button is tapped. I was following this video by LBTA on refactoring: https://youtu.be/F3snOdQ5Qyo
Formula Cell:
class FormulasCell: UITableViewCell {
var searchController: SearchController! {
didSet {
buttonStar.addTarget(searchController, action: #selector(searchController.handleFavoritedStar), for: .touchUpInside)
}
}
var buttonStar: UIButton = {
let button = UIButton()
button.setImage( #imageLiteral(resourceName: "GrayStar") , for: .normal)
button.tintColor = UIColor.greyFormula
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
}
Search Controller:
class SearchController: UIViewController, UITableViewDataSource, UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let formulaCell = FormulasCell()
formulaCell.searchController = self
setupTableView()
}
#objc func handleFavoritedStar() {
print("Added to Favorites")
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! FormulasCell
cell.selectionStyle = .none
cell.searchController = self
return cell
}

Swift unrecognized selector sent to instance error

I recently converted my project from Objective-C to Swift and in doing so I acquired this error whenever I click a button in the table view's cell. I have multiple cells being filled with information from a mysql server. I have two buttons, a follow button and followed button, when one is clicked the other is supposed to show. I've been working on this for a while but I've been stuck on this error.
Error I'm getting when I click the button in the tableview
CustomCellSwift[1425:372289] -[CustomCellSwift.ViewController followButtonClick:]: unrecognized selector sent to instance 0x100b13a40
In CustomCell.swift
class CustomCell: UITableViewCell {
#IBOutlet weak var firstStatusLabel: UILabel!
#IBOutlet weak var secondStatusLabel: UILabel!
#IBOutlet weak var myImageView: UIImageView!
#IBOutlet weak var followButton: UIButton!
#IBOutlet weak var followedButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
self.followButton.isHidden = true
self.followedButton.isHidden = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func populateCell(_ testObject: Test, isFollowed: Bool, indexPath: IndexPath, parentView: Any) {
// Loading Background Color
self.backgroundColor = UIColor.white
// Loading Status Labels
self.firstStatusLabel.text = testObject.testStatus1
self.secondStatusLabel.text = testObject.testStatus2
self.firstStatusLabel.isHidden = true
self.secondStatusLabel.isHidden = true
if isFollowed {
self.followedButton.tag = indexPath.row
self.followedButton.addTarget(parentView, action: Selector(("followedButtonClick")), for: .touchUpInside)
self.followedButton.isHidden = false
self.followButton.isHidden = true
// Status Labels
self.firstStatusLabel.isHidden = false
self.secondStatusLabel.isHidden = false
}
else {
self.followButton.tag = indexPath.row
self.followButton.addTarget(parentView, action: Selector(("followButtonClick:")), for: .touchUpInside)
self.followedButton.isHidden = true
self.followButton.isHidden = false
// Status Labels
self.firstStatusLabel.isHidden = false // True when done testing
self.secondStatusLabel.isHidden = false // True when done testing
}
}
}
ViewController.swift
CellForRowAt indexPath
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let CellIdentifier = "Cell"
var cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier) as! CustomCell
if cell != cell {
cell = CustomCell(style: UITableViewCellStyle.default, reuseIdentifier: CellIdentifier)
}
// Coloring TableView
myTableView.backgroundColor = UIColor.white
// Configuring the cell
var testObject: Test
if !isFiltered {
if indexPath.section == 0 {
testObject = followedArray[indexPath.row]
cell.populateCell(testObject, isFollowed: true, indexPath: indexPath, parentView: self)
}
else if indexPath.section == 1 {
testObject = testArray[indexPath.row]
cell.populateCell(testObject, isFollowed: false, indexPath: indexPath, parentView: self)
}
}
else {
testObject = filteredArray[indexPath.row] as! Test
cell.populateCell(testObject, isFollowed: false, indexPath: indexPath, parentView: self)
}
return cell
}
Follow Button Code
#IBAction func followButtonClick(sender: UIButton!) {
// Adding row to tag
let buttonPosition = (sender as AnyObject).convert(CGPoint.zero, to: self.myTableView)
if let indexPath = self.myTableView.indexPathForRow(at: buttonPosition) {
// Showing Status Labels
let cell = self.myTableView.cellForRow(at: indexPath) as! CustomCell
cell.firstStatusLabel.isHidden = false
cell.secondStatusLabel.isHidden = false
// Change Follow to Following
(sender as UIButton).setImage(UIImage(named: "follow.png")!, for: .normal)
cell.followButton.isHidden = true
cell.followedButton.isHidden = false
self.myTableView.beginUpdates()
// ----- Inserting Cell to Section 0 -----
followedArray.insert(testArray[indexPath.row], at: 0)
myTableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .fade)
// ----- Removing Cell from Section 1 -----
testArray.remove(at: indexPath.row)
let rowToRemove = indexPath.row
self.myTableView.deleteRows(at: [IndexPath(row: rowToRemove, section: 1)], with: .fade)
self.myTableView.endUpdates()
}
}
Unfollow button code is the same as the follow button.
I think the problem is in CustomCell.swift in the button selector(("")) but the error is saying -[CustomCellSwift.ViewController followButtonClick:] which means in ViewController in the follow button code but I don't know what to do anymore.
Two changes for Swift 3:
The selector should look like:
#selector(ClassName.followButtonClick(_:))
The function should have an underscore:
#IBAction func followButtonClick(_ sender: UIButton!) { ...
Notice that these two should be in the same class, otherwise, make sure you initialize the ClassName class.
If you want the selector method(followButtonClick(_:)) to be in the UITableViewCell class. Remove #IBAction(I don't think you need it there):
func followButtonClick(_ sender: UIButton!) { ...
For Swift3, you need to change the following:
self.followedButton.addTarget(parentView, action: Selector(("followedButtonClick")), for: .touchUpInside)
With:
self.followedButton.addTarget(parentView, action: #selector(self.followButtonClick(_:)), forControlEvents: .touchUpInside)
For Swift 2.2 with Xcode 8:
self.followedButton.addTarget(parentView, action: #selector(CustomCell.followButtonClick(_:)), forControlEvents: .TouchUpInside)

Delegate function from protocol not being called

I have a previously working delegate and protocol that since the conversion to Swift 3 is no longer being called.
protocol TaskCellDelegate {
func doneHit(_ cell : TaskCell)
}
class TaskCell : UITableViewCell {
var delegate : TaskCellDelegate?
#IBOutlet weak var label: UILabel!
#IBOutlet weak var detailLabel: UILabel!
#IBOutlet weak var _checkBox: M13Checkbox!
override func awakeFromNib() {
super.awakeFromNib()
let tap = UITapGestureRecognizer(target: self, action: #selector(TaskCell.buttonClicked(_:)))
tap.numberOfTapsRequired = 1
_checkBox.addGestureRecognizer(tap)
_checkBox.isUserInteractionEnabled = true
_checkBox.markType = .checkmark
_checkBox.boxType = .circle
_checkBox.stateChangeAnimation = .expand(.fill)
}
func buttonClicked(_ sender:UITapGestureRecognizer) {
delegate?.doneHit(self)
}
}
As you can see, when the _checkBox is tapped it should call the function doneHit in my class (not added because it doesn't seem necessary but I can) but I set a breakpoint and it's never called. I've set my delegate and conformed to the protocol in my class but nothing is happening. The doneHit function is supposed to update my backend but its not being called. If you need more info, I can provide.
Edit 1:
class TasksTVC: UITableViewController, TaskCellDelegate {
func doneHit(_ cell:TaskCell) {
if let indexPath = self.tableView.indexPath(for: cell) {
task = tasksInSectionArray[indexPath.section][indexPath.row]
if task.done == false {
cell._checkBox.setCheckState(.checked, animated: true)
task.done = true
task.completedBy = user
cell.detailLabel.text = "Completed By: \(task.completedBy)"
cell.label.textColor = UIColor.gray
print("cell checked")
}
else {
cell._checkBox.setCheckState(.unchecked, animated: true)
task.done = false
task.completedBy = ""
cell.detailLabel.text = ""
cell.label.textColor = UIColor.black
print("cell unchecked")
}
fb.updateTaskDoneBool(ref, taskID: task.id, taskDone: task.done)
fb.updateTaskCompletedBy(ref, taskID: task.id, taskCompletedBy: task.completedBy)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath) as! TaskCell
cell.selectionStyle = .none
task = tasksInSectionArray[indexPath.section][indexPath.row]
cell.label.text = task.title
if task.done == true {
cell._checkBox.setCheckState(.checked, animated: true)
cell.detailLabel.text = "Completed By: \(task.completedBy)"
cell.label.textColor = UIColor.gray
}
else {
cell._checkBox.setCheckState(.unchecked, animated: true)
cell.detailLabel.text = ""
cell.label.textColor = UIColor.black
}
doneHit(cell)
cell.delegate = self
return cell
}}
Looks like you didn't set correctly the delegate property in your TaskCell instance , I will make a very basic example hopefully it helps you to catch the issue:
Result (Edited)
Code
TableViewController
import UIKit
protocol TaskCellDelegate {
func doneHit(_ cell: TaskCell)
}
class TableViewController: UITableViewController, TaskCellDelegate {
func doneHit(_ cell: TaskCell) {
let alert = UIAlertController(
title: "Info",
message: "button touched in cell",
preferredStyle: .alert
)
present(alert, animated: true, completion: nil)
}
}
extension TableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TaskCell
cell.delegate = self // probably you forgot to set this part?
return cell
}
}
TaskCell (Edited)
Instead creating a new UITapGestureRecognizer to attach to the checkbox, you can use addTarget method to attach event handler for the UIControlEvents.valueChanged value.
import UIKit
import M13Checkbox
class TaskCell: UITableViewCell {
var delegate: TaskCellDelegate?
#IBOutlet weak var checkbox: M13Checkbox!
override func awakeFromNib() {
super.awakeFromNib()
checkbox.addTarget(self, action: #selector(buttonClicked), for: .valueChanged)
}
func buttonClicked() {
delegate?.doneHit(self)
}
}
There are following cases if delegate is not being called:
The action: buttonClicked is not being called.
The View Controller not Conforming to the protocol.
class ViewController: UIViewController, TaskCellDelegate {
The protocol method not implemented inside View Controller.
func doneHit(_ cell : TaskCell) {
print("delegate implementation called")
}
Delegate not assigned in cellForRowAtIndexPathMethod:
cell.delegate = self

Resources