I will give an example code:

There is a View:

import UIKit protocol ContactsCellDelegate: class { func fooMethod(phone: String) } class ContactsCell: UITableViewCell, UITextViewDelegate { @IBOutlet weak var phone: UITextView! { didSet { phone.delegate = self } } weak var delegate: ContactsCellDelegate? func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool { self.delegate?.fooMethod(self.phone.text) return true } } 

There is a controller:

 import UIKit class AboutCompanyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, ContactsCellDelegate { let contacts = ["phone1", "phone2", "phone3"] func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contacts.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("contactCell", forIndexPath: indexPath) as! ContactsCell cell.phone.text = self.contacts[indexPath.row] return cell } // ContactsCellDelegate method func fooMethod(phone: String) { NSLog("Phone number = \(phone)") } } 

The task is to process tap by UITextView (call to phone number, which is in UITextView) and execute the code in processing. Everything works without delegation, if you place the processing code directly into the View method:

 func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool { NSLog("Phone number = \(phone.text)") return true } 

But, thus, some business logic is present in the View and, I would like, to bring all this to the controller. With delegation, call the delegate method:

 self.delegate?.fooMethod(self.phone.text) 

does not work.

The question is why doesn't it work?

PS: Due to the circumstances, I am working on finalizing the iOS application (I myself am an Android developer), so please do not kick it if the solution floats somewhere on the surface.

    1 answer 1

    So sign the cells on it:

     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("contactCell", forIndexPath: indexPath) as! ContactsCell cell.delegate = self cell.phone.text = self.contacts[indexPath.row] return cell }