2016-12-23 57 views
0

我試圖在Swift上實現委託模式。該過程包含一個彈出窗口,該窗口在textView的文本選擇中從UIMenuItem顯示。這個彈出窗口是一個包含一些顏色的TableViewController。點擊單元格(或顏色)時,所選文本會將其顏色從黑色更改爲所選顏色。我在發送級別以下協議:委派不工作Swift

protocol SelectedColorDelegate { 
func didSelectColorCell(color: UIColor) 
} 

然後,在發送I類創建該屬性:

var colorCellDelegate: SelectedColorDelegate? 

在tableViewController(酥料餅)的方法didSelectRowAtIndexPath方法即發送級別,我分配所需的參數:

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

在作爲我的ViewController設置協議SelectedColorDelegate我接收類,並符合它瓦特第i這種方法,目的是改變文字顏色:

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 
} 

但最後的方法不會被調用,敲擊酥料餅的細胞什麼都不做,我錯過什麼或做錯了嗎?謝謝!! :)

+0

你可以把斷點與'didSelectRowAt'功能並檢查是否COLLED? –

+0

您是否將ViewController分配給colorCellDelegate? –

+1

popover?.delegate = self;確保將這些委託分配給Viewcontroller。 – Himanshu

回答

1

,首先因爲只有定義協議類

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

其次,我們希望我們的代表保留

weak var colorCellDelegate: SelectedColorDelegate? 

最後,設置代理,當你表現出另一種觀點或viewDidLoad中如:

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

     self.colorCellDelegate = self 
    } 
} 

Tutorial - How To Make Weak Delegates In Swift

+0

我設法找到了我的錯誤,但是如果我將委託設置爲弱引用,那麼編譯器會抱怨說「weak只能應用於類和類綁定的協議類型」,而不是簡單的協議我實現了,所以我的協議必須是僅限類的類型。謝謝! –

+0

@MarilynGarcía將你的協議定義爲僅適用於類。尋找我編輯的答案 –

0

您是否:xxTableViewController.colorCellDelegate = self in xxViewController?

而且你的委託聲明應該是弱:

weak var colorCellDelegate: SelectedColorDelegate? 
+0

ViewController對colorCellDelegate的判斷是否進入viewDidLoad()? –

+0

@MarilynGarcía,你在那裏創建xxTableViewController:let xxTableViewController = XXTableViewController(); xxTableViewController.colorCellDelegate = self –

0

在PopOverTableViewController,設置應該看起來像 -

class PopOverTableViewController: UITableViewController, SelectedColorDelegate { 

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