Delegation not working Swift

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-25 04:13:23

问题


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


回答1:


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:


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

And your delegate declaration should be weak:

weak var colorCellDelegate: SelectedColorDelegate?



回答3:


In PopOverTableViewController, setup should look like -

class PopOverTableViewController: UITableViewController, SelectedColorDelegate {

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


来源:https://stackoverflow.com/questions/41296115/delegation-not-working-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!