簡體   English   中英

代表團不工作迅速

[英]Delegation not working Swift

我正在嘗試在Swift上實現委托模式。 該過程包含一個彈出框,該彈出框從UIMenuItem顯示在textView的文本選擇中。 此彈出窗口是一個TableViewController,其中包含一些顏色。 輕擊單元格(或顏色)時,所選文本的顏色從黑色更改為所選顏色。 我在發送類中具有以下協議:

protocol SelectedColorDelegate {
func didSelectColorCell(color: UIColor)
}

然后,在發送類中,我創建了以下屬性:

var colorCellDelegate: SelectedColorDelegate?

在作為發送類的tableViewController(popover)的didSelectRowAtIndexPath方法中,我分配了必需的參數:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let color = arrayOfColorValues[indexPath.row]
    self.colorCellDelegate?.didSelectColorCell(color: color)
}

在作為ViewController的接收類中,我設置了協議SelectedColorDelegate,並使用此方法使其與之一致,旨在更改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
}

但是永遠不會調用最后一個方法,點擊彈出窗口的單元格無濟於事,我錯過了什么或做錯了什么? 謝謝!! :)

首先,將您的協議僅定義為類

protocol SelectedColorDelegate: class {
    func didSelectColorCell(color: UIColor)
}

其次,我們希望弱勢保留代表

weak var colorCellDelegate: SelectedColorDelegate?

最后,當您顯示其他視圖或在viewDidLoad中時設置委托,例如:

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

        self.colorCellDelegate = self
    }
}

教程-如何在Swift中使弱代表

您是否做過: xxTableViewController.colorCellDelegate = self在xxViewController中?

並且您的委托聲明應該是弱的:

weak var colorCellDelegate: SelectedColorDelegate?

在PopOverTableViewController中,設置應類似於-

class PopOverTableViewController: UITableViewController, SelectedColorDelegate {

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM