2015-07-20 233 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 

    }