Using protocols for detail view controllers

Hi, I’m working on the Checklist app, and I’m trying to reduce code duplication in the ListDetailViewController and the ItemDetailViewController. To do so, I first created a DetailViewController protocol with an extension, to provide a default implementation for the textField(shouldChangeCharacterInRange:) method.

protocol DetailViewController: UITableViewController, UITextFieldDelegate {
    var doneBarButton: UIBarButtonItem! { get }
}

extension DetailViewController {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let oldText = textField.text!
        let newText = oldText.replacingCharacters(in: Range(range, in: oldText)!, with: string)
        doneBarButton.isEnabled = !newText.isEmpty
        return true
    }
}

The problem appears when I make ListDetailViewController adopt this protocol; I get the following warning : “Non-’@objc’ method ‘textField(_:shouldChangeCharactersIn:replacementString:)’ does not satisfy optional requirement of ‘@objc’ protocol ‘UITextFieldDelegate’”
Could you help me ?

Hi, Have a look on this stackoverflow answer, It is explaining about the same issue in detail, check it here -> Non-’@objc’ method does not satisfy optional requirement of ‘@objc’ protocol

Thank you for the link! It looks like it’s simply not possible, so I’ll stick to the code in the book.

1 Like

You are welcome ~ Happy coding :slight_smile:

This topic was automatically closed after 166 days. New replies are no longer allowed.