委派不起作用 Swift [英] Delegation not working Swift

查看:73
本文介绍了委派不起作用 Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Swift 上实现委托模式.该过程包括一个弹出窗口,该弹出窗口从文本视图上的文本选择中的 UIMenuItem 显示.这个弹出框是一个包含一些颜色的 TableViewController.当点击单元格(或颜色)时,所选文本的颜色会从黑色变为所选颜色.我在发送类中有以下协议:

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?

在发送类的tableViewController(popover)的didSelectRowAtIndexPath方法中,我分配了需要的参数:

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

在我的 ViewController 接收类中,我设置了 SelectedColorDelegate 协议,并使用此方法符合它,旨在更改 textColor:

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

推荐答案

首先定义你的协议只针对类

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?

最后在显示其他视图或在 viewDidLoad 中设置委托,例如:

Finally set delegate when you show other view or in viewDidLoad eg:

class YourViewController: SelectedColorDelegate {
    final override func viewDidLoad() {
        super.viewDidLoad()

        self.colorCellDelegate = self
    }
}

教程 - 如何在 Swift 中创建弱委托

这篇关于委派不起作用 Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆