我试图在另一个类中调用协议委托。第一个类(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在viewController类中可以正常工作。请问你能帮我看看有什么不对吗?
答案 0 :(得分:0)
您的weak var delegate:BWWalkthroughViewControllerDelegate?
是一个可选变量,并且未在您显示的代码中的任何位置分配,因此它将为零。你必须在某处实例化它才能工作。
这样做的好方法是:
class BWWalkthroughViewController {
let bwWalkthroughPageViewController = BWWalkthroughPageViewController()
var bwWalkthroughViewControllerDelegate : BWWalkthroughViewControllerDelegate!
init() {
bwWalkthroughViewControllerDelegate = bwWalkthroughPageViewController as BWWalkthroughViewControllerDelegate
}
}
需要注意的是,为代理人命名有意义的名称通常是一种好习惯。关键字“委托”通常用于许多类并受到限制。更详细的名称将消除覆盖原始代表的机会,并且如果您有多个名称,将有助于识别每个代表。