2015-07-20 231 views
2

我想在Swift中創建一個協議和委託,但我遇到了一些問題。我想在表視圖的單元格中有一個切換按鈕。這裏是我的協議:在Swift中的協議和授權

import Foundation 
import UIKit 

protocol CellProtocol { 
    func onSwitchToogle (sender : AnyObject , onCell : UITableViewCell) 
} 

這裏是我的手機類:

import UIKit 

class Cell: UITableViewCell { 

    @IBOutlet weak var label: UILabel! 
    @IBOutlet weak var flag: UISwitch! 
    var cellDelegate:CellProtocol! 

    @IBAction func Toogle(sender: AnyObject) { 
     if((cellDelegate?.onSwitchToogle(sender, onCell: self)) != nil){ 

     } 
    } 
} 

這裏是我的ViewController:

import UIKit 

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CellProtocol {  
    func onSwitchToogle(sender: AnyObject, onCell: UITableViewCell) { 

    } 

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return 1 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! Cell 
     cell.label.text = "sadsad" 
     return cell 
    } 
} 

的問題是:它永遠不會在if條件進入我的開關的IBAction,它永遠不會進入ViewController的方法。

+2

加上...'onSwitchToogle()'不會返回任何東西,所以我甚至不知道你要用這​​個'if'語句來做什麼...... – nhgrif

+0

不要讓你的委託隱式地解開! –

回答

1

幾件事情:

  1. 你要確保你指定的代表在cellForRowAtIndexPath

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! Cell 
        cell.cellDelegate = self 
        cell.label.text = "sadsad" 
        return cell 
    } 
    
  2. 請確保您沒有強大的參考週期,使cellDelegate財產weak

    weak var cellDelegate: CellProtocol! 
    
  3. 爲了讓你有協議類型弱引用,你必須使協議的class協議:

    protocol CellProtocol : class { 
        func onSwitchToggle (sender : AnyObject, onCell : UITableViewCell) 
    } 
    
  4. 顯然你只是想打電話onSwitchToggle如果代表已設置(使用可選鏈接):

    @IBAction func toggle(sender: AnyObject) { 
        cellDelegate?.onSwitchToggle(sender, onCell: self) 
    } 
    

    不需要測試以確保委託實現該方法,因爲如果視圖控制器符合協議,它必須實現該方法。

請原諒我,但我換了一個方法名(切換VS的toogle,開始用小寫字母方法名稱等),但希望這說明了關鍵點。

+0

我將聲明委託爲可選,而不是隱式解包可選:'weak var cellDelegate:CellProtocol?' –

+0

這取決於OP的意圖。如果應用程序的設計使某些單元格具有代表性,而其他單元格不具有代表性,那麼我同意,它應該是可選的。如果'Cell'類的_all_成員將_always_有一個'cellDelegate',那麼我個人更喜歡隱式地解開,以使這個意圖清晰。 – Rob

0

在的cellForRowAtIndexPath設立代表自我:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

     let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! Cell 

     cell.label.text = "sadsad" 
     cell.cellDelegate = self 

     return cell 

    }