gpt4 book ai didi

ios - @obj 协议(protocol)委托(delegate)方法在第二类中不起作用。 swift

转载 作者:行者123 更新时间:2023-11-30 14:15:35 24 4
gpt4 key购买 nike

我正在尝试在另一个类中调用协议(protocol)委托(delegate)。第一个类(ViewController)有效,但我实现的第二个类不显示任何数据。我使用自动填充选项添加了它,因此它不会给出错误。它只是没有做任何事情。

发送者类别

@objc protocol BWWalkthroughViewControllerDelegate{

@objc optional func walkthroughPageDidChange(pageNumber:Int) // Called when current page changes

}

@objc class BWWalkthroughViewController: UIViewController, UIScrollViewDelegate, ViewControllerDelegate {

// MARK: - Public properties -

weak var delegate:BWWalkthroughViewControllerDelegate?


var currentPage:Int{ // The index of the current page (readonly)
get{
let page = Int((scrollview.contentOffset.x / view.bounds.size.width))
return page
}
}


// MARK: - Private properties -

let scrollview:UIScrollView!
var controllers:[UIViewController]!
var lastViewConstraint:NSArray?
var shouldCancelTimer = false
var aSound: AVAudioPlayer!
var isForSound: AVAudioPlayer!
var alligatorSound: AVAudioPlayer!
var audioPlayer = AVAudioPlayer?()
var error : NSError?
var soundTrack2 = AVAudioPlayer?()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var audioPlayerAnimalSound = AVAudioPlayer?()
var audioPlayerAlphabetSound = AVAudioPlayer?()
var audioPlayerFullPhraze = AVAudioPlayer?()
var audioPlayerPhonics = AVAudioPlayer?()

删除代码以节省空间继续:

  /**
Update the UI to reflect the current walkthrough situation
**/

private func updateUI(){

// Get the current page

pageControl?.currentPage = currentPage


// Notify delegate about the new page

delegate?.walkthroughPageDidChange?(currentPage)

}

接收者类别

class BWWalkthroughPageViewController: UIViewController, BWWalkthroughPage, ViewControllerDelegate, BWWalkthroughViewControllerDelegate {

第二类函数。

func walkthroughPageDidChange(pageNumber: Int) {
println("current page 2 \(pageNumber)")

}
然而,walkthroughPageDidChange 在 vi​​ewController 类中确实有效。请您帮我看看哪里出了问题?

最佳答案

您的 weak var delegate:BWWalkthroughViewControllerDelegate? 是一个可选变量,它没有在您提供的代码中的任何位置分配,因此它将为零。您必须在某个地方实例化它才能工作。

这样做的一个好方法是:

class BWWalkthroughViewController {
let bwWalkthroughPageViewController = BWWalkthroughPageViewController()
var bwWalkthroughViewControllerDelegate : BWWalkthroughViewControllerDelegate!

init() {
bwWalkthroughViewControllerDelegate = bwWalkthroughPageViewController as BWWalkthroughViewControllerDelegate
}
}

需要注意的是,使用有意义的名称来命名委托(delegate)通常是一种很好的做法。关键字“delegate”经常用于许多类并且受到限制。更详细的名称将消除覆盖原始委托(delegate)的机会,并且如果您有多个委托(delegate),将有助于识别每个委托(delegate)。

关于ios - @obj 协议(protocol)委托(delegate)方法在第二类中不起作用。 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31236264/

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