iOS Delegate is not being set and is returning nil (Swift)

patkil

I am getting nil when I try to set a delegate, and can't figure out why the delegate is not properly set.

I have a View Controller ListViewController which I add a subview to, musicPlayer. musicPlayer is a UIView which has some buttons that should trigger actions in ListViewController when clicked.

musicPlayer is set up like this:

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 is set up like this:

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")
}

When I run this, println(myDelegate) is nil and println("Your delegate is working") never gets called. Any suggestions on how to fix this?

rdelmar

If I understand your setup correctly, the problem is that your setting the delegate on an instance of musicPlayer (that really should be MusicPlayer with a capital M) that never is on screen -- you create that instance, but you never do anything with it. You should set the delegate on playerSubview, since that's the instance that you add as a subview.

@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)
}

Notice that I changed the downcast to "as musicPlayer" instead of "as UIView", otherwise the compiler will complain when you try to set the delegate.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related