简体   繁体   中英

Swift Delegate is not being called

I have completed all the needed code for delegate to work. In my viewcontroller: class ViewController: UIViewControllerCustomViewDelegate I also have this:

   override func viewDidLoad() {
            super.viewDidLoad()
            let myCustomView = Bundle.main.loadNibNamed("ImageHeaderView", owner: self, options: nil)?[0] as! ImageHeaderView
        myCustomView.delegate = self

        }
func goToNextScene() {
        print("GOTOSCENE2")
            }

And in my custom view I have this:

import UIKit

protocol CustomViewDelegate: class {         // make this class protocol so you can create `weak` reference
    func goToNextScene()
}

@available(iOS 10.0, *)
class ImageHeaderView : UIView {

    @IBOutlet weak var followme: UISwitch!
    @IBOutlet weak var profileImage : UIImageView!
    @IBOutlet weak var backgroundImage : UIImageView!

    weak var delegate: CustomViewDelegate?

    override func awakeFromNib() {
        super.awakeFromNib()
        self.backgroundColor = UIColor(hex: "E0E0E0")
        self.profileImage.layer.cornerRadius = self.profileImage.frame.size.height / 2
        self.profileImage.clipsToBounds = true
        self.profileImage.layer.borderWidth = 1
        self.profileImage.layer.borderColor = UIColor.white.cgColor
        //self.profileImage.setRandomDownloadImage(80, height: 80)
        //self.backgroundImage.setRandomDownloadImage(Int(self.frame.size.width), height: 100)
    }
    @IBAction func followme(_ sender: AnyObject) {
         UserDefaults.standard.set(followme.isOn, forKey: "followme")
    }
    @IBAction func logout(_ sender: AnyObject) {
        delegate?.goToNextScene()
        print("GOTOSCENE")
    }
}

There is are no errors thrown but when I click/tap the button, nothing happens. It just prints "GOTOSCENE".

What I feel is

Your problem is right here

override func viewDidLoad() {
            super.viewDidLoad()
            let myCustomView = Bundle.main.loadNibNamed("ImageHeaderView", owner: self, options: nil)?[0] as! ImageHeaderView
        myCustomView.delegate = self

        }

I think you have added imageHeaderview from storyboard and in viewdidload you are creating new object of ImageHeaderView and assigning delegate to newly created object.

Try to outlet your ImageHeaderView and assign delegate to outleted object.

Hope this will fix your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM