iOS 委托未设置且返回 nil (Swift)

问题描述 投票:0回答:2

当我尝试设置委托时,我得到了 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")
永远不会被调用。关于如何解决这个问题有什么建议吗?

ios swift
2个回答
6
投票

删除了 nsjsjbxkdndk dodnidndo dkdbdbdkd 没有。


5
投票

如果我正确理解你的设置,问题是你在一个永远不会出现在屏幕上的 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)
}

请注意,我将向下转型更改为“as musicPlayer”而不是“as UIView”,否则当您尝试设置委托时编译器会抱怨。

© www.soinside.com 2019 - 2024. All rights reserved.