我已经完成了委托工作所需的所有代码。在我的视图控制器中:class ViewController: UIViewControllerCustomViewDelegate我也有这个:

   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")
            }

在我的自定义视图中,我有以下内容:
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")
    }
}

没有引发任何错误,但是当我单击/点击按钮时,什么也没有发生。它仅打印“GOTOSCENE”。

最佳答案

我的感觉是

你的问题就在这里

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

        }

我认为您已从情节提要中添加了imageHeaderview,并在viewdidload中创建了ImageHeaderView的新对象并将委托分配给新创建的对象。

尝试退出ImageHeaderView并将委托分配给已退出的对象。

希望这能解决您的问题。

10-07 16:06