当我尝试设置委托时,我变为nil,并且无法弄清楚为什么委托没有正确设置。
我有一个视图控制器ListViewController
我在其中添加了一个子视图musicPlayer
。 musicPlayer
是一个UIView,其中有一些按钮可以在单击时触发ListViewController
中的操作。
musicPlayer
设置如下:
protocol MusicPlayerControlsDelegate {
func playPauseClicked()
}
class musicPlayer: UIView {
var myDelegate: MusicPlayerControlsDelegate?
//this should trigger function in delegate
@IBAction func playOrPause(sender: AnyObject) {
println(myDelegate?)
myDelegate?.playPauseClicked()
}
ListViewController
设置如下:
class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MusicPlayerControlsDelegate {
var musicControls:musicPlayer = musicPlayer()
override func viewDidLoad() {
musicControls.myDelegate = self
}
//adds musicPlayer nib as a subview to ListViewController
@IBAction func playInApp(sender: AnyObject) {
let bundle = NSBundle(forClass: musicPlayer.self)
var playerSubview = bundle.loadNibNamed("musicPlayerSubview", owner: nil, options: nil)[0] as UIView
playerSubview.frame = CGRectMake(0, self.view.frame.width + 79, self.view.frame.width, 200)
self.view.addSubview(playerSubview)
}
func playPauseClicked() {
println("Your delegate is working")
}
运行时,println(myDelegate)
为nil
,println("Your delegate is working")
永远不会被调用。有关如何解决此问题的任何建议吗?
答案 0 :(得分:4)
如果我理解你的设置正确,问题是你在一个从不在屏幕上的musicPlayer实例(真的应该是带有大写字母M的MusicPlayer)上设置委托 - 你创建了那个实例,但是你永远不会什么都有它。您应该在playerSubview上设置委托,因为那是您添加为子视图的实例。
@IBAction func playInApp(sender: AnyObject) {
let bundle = NSBundle(forClass: musicPlayer.self)
var playerSubview = bundle.loadNibNamed("musicPlayerSubview", owner: nil, options: nil)[0] as musicPlayer
playerSubview.frame = CGRectMake(0, self.view.frame.width + 79, self.view.frame.width, 200)
playerSubview.myDelegate = self
self.view.addSubview(playerSubview)
}
请注意,我将向下转换为"作为musicPlayer"而不是"作为UIView",否则编译器会在您尝试设置委托时抱怨。
答案 1 :(得分:4)
有时,你忘记了segue
if(segue.identifier == "YourSegueIdentifier"){
let v = segue.destinationViewController as! YourViewController
v.delegate = self
}
这一行非常重要,因为如果你忘记了它,那么它将不起作用
v.delegate = self