此应用使用可可故事板。
class WindowController: NSWindowController, ControllerDelegate {
@IBOutlet var progressIndicator: NSProgressIndicator!
override func windowDidLoad() {
super.windowDidLoad()
if let window = window, let screen = NSScreen.main() {
let myVc = window.contentViewController as! MainViewController
myVc.delegate = self
}
}
// These methods are not being called
func runProgress() {
print("runProgress") // not being called
progressIndicator.isHidden = false
progressIndicator.isIndeterminate = true
progressIndicator.usesThreadedAnimation = true
progressIndicator.startAnimation(nil)
}
func stopProgress() {
progressIndicator.stopAnimation(nil)
progressIndicator.isHidden = true
}
}
协议ControllerDelegate
protocol ControllerDelegate: class {
func runProgress()
func stopProgress()
}
MainViewController
class MainViewController: NSViewController {
@IBOutlet weak var collectionView: NSCollectionView!
var images = [Image]()
weak var delegate:ControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
此处设置代理无效
delegate?.runProgress() // No effect on setting the delegate here
fetchDatafrom(url: URL(string:editorApi)!) {
self.pxImages = $0!
self.collectionView.reloadData()
self.delegate?.stopProgress() // this works correctly
}
} }
如果我将委托放在viewWillLayout()
中,而不是称为
override func viewWillLayout() {
delegate?.runProgress()
}