0

Приведу пример кода:

есть 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

    }

}

Есть контроллер:

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)")
    }

}

Стоит задача - обработать тап по UITextView (звонок на номер тлф., который в UITextView) и выполнить код в обработке. Все работает без делегирования, если поместить код обработки непосредственно в метод View:

func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {

    NSLog("Phone number = \(phone.text)")

    return true

}

Но, таким образом, некоторая бизнес-логика присутствует во View и, хотелось бы, все это вынести в контроллер. С делегированием, вызов метода делегата:

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

не срабатывает.

Вопрос - почему не срабатывает?

P.S.: В связи со сложившимися обстоятельствами, занимаюсь доработкой iOS приложения (сам я - Android developer), поэтому прошу сильно не пинать, если решение плавает где-то на поверхности.

1 ответ 1

1

Так подпишите ячейки на него:

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
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.