2015-09-06 149 views
1

我在我的项目中实现了side menu from github。我正在尝试在其中添加。通过这种方式,当cell被选中时,另一个类(主要的viewController)中的函数将被调用。这里是我的代码:协议委托不会调用函数

tableView.swift

protocol menuTableViewProtocol { 
    func didSelectCell(SelectedCellNumber : Int) 
} 

var delegate : menuTableViewProtocol? 

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    self.delegate?.didSelectCell(indexPath.row) 
} 

mainVC.swift 

class MainViewController: UIViewController, menuTableViewProtocol { 

    ... 

    // Conforming to Protocal 
    func didSelectCell(SelectedCellNumber: Int) 
    { 
     switch SelectedCellNumber { 
     case 0: 
      println("0") 

     case 1: 
      println("1") 

     case 2: 
      println("2") 

     default: 
      println("0101010") 
     } 
    } 
} 

当我运行应用程序,并选择一个细胞,没有任何反应。 didSelectRowAtIndexpath确实被调用。 (我插入了println并打印出来),但didSelectCellprotocol function)未被调用。我做错了什么,我能做些什么来解决它?

+0

在你mainVC你符合这个协议,并已设置的tableView委托的实例作为自我?你能否显示该代码? –

+0

我按照协议编辑了问题。我以为我错过了一些东西。我在mainVC.swif **中没有tableView.swift **的实例,因此无法使委托自行创建。 'tableView' get在navigationController.swift中创建。 https://github.com/evnaz/ENSwiftSideMenu/blob/master/Example/SwiftSideMenu/MyNavigationController.swift而我只在mainVC.swift中调用一个方法。 ('toggleSideMenuView') – Jessica

+0

对不起,但我对你正在使用的第三方组件没有太多的想法,但理想情况下,你应该有一个实例,并将委托设置为self,以使委托实际工作。或者您也可以查看通知,以便它适合您的需要。 –

回答

0

正如你在你的评论中提到的那样,你不能将委托设置为self,并且你的类之间没有直接关系,所以你应该使用NSNotificationCenter而不是协议和委托。

// A类(mainVC.swift)

//Add Observer in init method 
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handler:", name: "MyNotification", object: nil) 

//Handler 
func handler(notif: NSNotification) { 
    println("MyNotification was handled"); 
    println("userInfo: \(notif.userInfo)"); 
    println("SelectedCellNumber \(notif.userInfo!["selectedCellNumber"])"); //Validate userInfo here. it could be nil 

} 

// B类(tableView.swift)

// Call from any method 
NSNotificationCenter.defaultCenter().postNotificationName("MyNotification", object: nil, userInfo: ["selectedCellNumber" : indexPath.row]); 

为更详细地,可以按照一些教程;

http://derpturkey.com/nsnotificationcenter-with-swift/

+0

感谢您的回答!我如何将'indexPath.row'传递给'mainVC.swift'? – Jessica

+0

@Jessica查看我更新的帖子 – Shoaib