委派不起作用 Swift

编程入门 行业动态 更新时间:2024-10-27 02:22:11
本文介绍了委派不起作用 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

本文发布于:2023-11-27 20:38:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639518.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!