我正在尝试从updateProgress
对象调用函数LoadingDataHelper
,但我的代理没有被调用。我认为问题在于LoadingDataHelper
与LoadingDataViewController
没有关联(我的意思是,当您拥有UIView
和viewController
时。
LoadingDataHelper
protocol LoadingNewDataDelegate: class {
func updateProgress(progress : Float)
}
class LoadingDataHelper: NSObject {
var delegate: LoadingNewDataDelegate?
static let shared = LoadingDataHelper() // shared instance
func loginUser() {
//more code
updateProgressInViewController()
//more code
}
func updateProgressInViewController() {
delegate?.updateProgress(0.3)
}
}
LoadingDataViewController
class LoadingDataViewController: UIViewController, LoadingNewDataDelegate {
let loadingDataHelper: LoadingDataHelper = LoadingDataHelper()
override func viewDidLoad() {
super.viewDidLoad()
loadingDataHelper.delegate = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if (NSUserDefaults.standardUserDefaults().boolForKey("approvedTermsOfUse")) {
self.updateProgress(0.1)
LoadingDataHelper.shared.loginUser()
} else {
self.askForTerms()
}
}
func updateProgress(progress : Float) {
self.progressBar.setProgress(progress, animated: true)
self.progressBar.setNeedsDisplay()
}
}
有没有办法解决这个问题?
答案 0 :(得分:0)
上面的代码有一些错误: 在LoadingDataViewController中,您要为 LoadingDataHelper 类创建静态属性,并将委托设置为该类。但是你用直接电话叫“loginUser”。
您需要更改如下:
class LoadingDataViewController: UIViewController, LoadingNewDataDelegate {
**//Change to shared initialisation of object//**
let loadingDataHelper: LoadingDataHelper = LoadingDataHelper.shared
override func viewDidLoad() {
super.viewDidLoad()
loadingDataHelper.delegate = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if (NSUserDefaults.standardUserDefaults().boolForKey("approvedTermsOfUse")) {
self.updateProgress(0.1)
**//Call using static object instead of new instance or direct call//**
loadingDataHelper.loginUser()
} else {
self.askForTerms()
}
}
func updateProgress(progress : Float) {
self.progressBar.setProgress(progress, animated: true)
self.progressBar.setNeedsDisplay()
}
}
这将使您的控制器获得委托回电。