Delegation not working Swift

10.2k views Asked by At

I'm trying to implement the delegation pattern on Swift. The process consists in a popover that is displayed from a UIMenuItem in a text selection on a textView. This popover is a TableViewController that contains some colors. When a cell (or color) is tapped, the selected text changes its color from black to the selected color. I have the following protocol in the sending class:

protocol SelectedColorDelegate {
func didSelectColorCell(color: UIColor)
}

Then in the sending class I created this property:

var colorCellDelegate: SelectedColorDelegate?

In the method didSelectRowAtIndexPath of the tableViewController (popover) that is the sending class, I assigned the required parameter:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let color = arrayOfColorValues[indexPath.row]
    self.colorCellDelegate?.didSelectColorCell(color: color)
}

In my receiving class that is a ViewController I set the protocol SelectedColorDelegate, and conformed to it with this method, aimed to change the textColor:

func didSelectColorCell(color: UIColor) {
    let textRange = noteTextView.selectedRange
    let string = NSMutableAttributedString(attributedString: noteTextView.attributedText)
    string.addAttribute(NSForegroundColorAttributeName, value: color, range: textRange)
    noteTextView.attributedText = string
    noteTextView.selectedRange = textRange
}

But the last method is never called, tapping the cell of the popover does nothing, what am I missing or doing wrong? Thanks!! :)

3

There are 3 answers

2
Adrian Bobrowski On BEST ANSWER

First of all define your protocol as only for classes

protocol SelectedColorDelegate: class {
    func didSelectColorCell(color: UIColor)
}

Secondly we want our delegate to be weakly retained

weak var colorCellDelegate: SelectedColorDelegate?

Finally set delegate when you show other view or in viewDidLoad eg:

class YourViewController: SelectedColorDelegate {
    final override func viewDidLoad() {
        super.viewDidLoad()

        self.colorCellDelegate = self
    }
}

Tutorial - How To Make Weak Delegates In Swift

2
Yun CHEN On

Did you do: xxTableViewController.colorCellDelegate = self in xxViewController?

And your delegate declaration should be weak:

weak var colorCellDelegate: SelectedColorDelegate?
0
BaSha On

In PopOverTableViewController, setup should look like -

class PopOverTableViewController: UITableViewController, SelectedColorDelegate {

    override func viewDidLoad() {
          super.viewDidLoad()
          self.colorCellDelegate = self
    }
}