[英]Swift Delegate is never called
I know the question is already here in the forum but I don't know why my delegate doesn't work.我知道这个问题已经在论坛中了,但我不知道为什么我的代表不起作用。 I work with them for the first time, by the way.顺便说一句,我是第一次和他们一起工作。
Here is the code这是代码
ViewController:视图控制器:
class ViewController: UIViewController, ContainerViewControllerDelegate{
override func viewDidLoad() {
super.viewDidLoad()
let controller = ContainerViewController()
controller.containerDelegate = self
}
func didScrollChangeAppearanceBarButtonItem(change: Bool) {
if(change == true){
print("true")
}else{
print("false")
}
}
}
ContainerView:容器视图:
protocol ContainerViewControllerDelegate {
func didScrollChangeAppearanceBarButtonItem(change: Bool)
}
class ContainerViewController: UIViewController, UIScrollViewDelegate{
var containerDelegate: ContainerViewControllerDelegate?
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if(velocity.y>0) {
containerDelegate?.didScrollChangeAppearanceBarButtonItem(change: false)
print("1")
} else {
containerDelegate?.didScrollChangeAppearanceBarButtonItem(change: true)
print("2")
}
}
}
What I am trying to do: When I scroll I want to send a bool to my ViewController.我正在尝试做的事情:当我滚动时,我想向我的 ViewController 发送一个布尔值。 When the bool == true I want to something and when the bool == false I want to do something else.当 bool == true 我想做某事时,当 bool == false 我想做其他事情时。
I hope somebody can help me:)我希望有人可以帮助我:)
instead of this:而不是这个:
let controller = ContainerViewController()
controller.containerDelegate = self
create the variable outside viewDidLoad():在 viewDidLoad() 之外创建变量:
var controller:ContainerViewController!
override func viewDidLoad() {
super.viewDidLoad()
controller = ContainerViewController()
controller.containerDelegate = self
}
The reason is that the controller being initialized inside the viewDidLoad gets deallocated once the viewDidLoad function reaches its end原因是,一旦 viewDidLoad function 到达终点,在 viewDidLoad 中初始化的 controller 就会被释放
Edit编辑
I will elaborate, if you are trying to access your other view controller by segue, this is a wrong way.我将详细说明,如果您尝试通过 segue 访问您的其他视图 controller,这是错误的方式。 Instead do this:而是这样做:
self.performSegueWithIdentifier("your identifier", sender: self)
then add a function:然后添加一个 function:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "Your identifier") {
guard let controller = segue.destination as? ContainerViewController else { return }
controller.delegate = self
}
}
You are allocating a ContainerViewController, which is deallocated about a microsecond later when the code leaves viewDidLoad, because there are no references to it.您正在分配一个 ContainerViewController,当代码离开 viewDidLoad 时,它会在大约一微秒后被释放,因为没有对它的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.