gpt4 book ai didi

iOS Delegate 未设置并返回 nil (Swift)

转载 作者:搜寻专家 更新时间:2023-10-30 22:35:53 25 4
gpt4 key购买 nike

当我尝试设置委托(delegate)时,结果为 nil,并且无法弄清楚为什么委托(delegate)未正确设置。

我有一个 View Controller ListViewController,我向其添加了一个 subview musicPlayermusicPlayer 是一个 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") 永远不会被调用。有关如何解决此问题的任何建议?

最佳答案

有时候,你忘记了segue

if(segue.identifier == "YourSegueIdentifier"){
let v = segue.destinationViewController as! YourViewController

v.delegate = self

}

这一行很重要,因为如果你忘记了它,它将无法工作

v.delegate = self

关于iOS Delegate 未设置并返回 nil (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27519392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com