Search code examples
iosswiftuitableviewprotocolsdelegation

Delegation not working Swift


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!! :)


Solution

  • 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