点击New Account Label切换页面时应用崩溃,请求技术协助
iOS点击Label跳转页面崩溃问题排查与修复
问题原因分析
手势识别器绑定对象错误
创建UITapGestureRecognizer时,target传入了LoginViewController.self(类对象),但newAccountLabelTapped是实例方法,只能由ViewController的实例调用,绑定类对象会导致无法找到对应方法引发崩溃。响应方法参数类型不匹配
响应方法的参数声明为UIButton,但实际触发手势的是UITapGestureRecognizer,类型不匹配会导致运行时无法正确解析参数,引发崩溃。
修正后的代码
Label创建代码
lazy var newAccountLabel: UILabel = { let newAccountLabel = UILabel() newAccountLabel.text = " New Account" newAccountLabel.isUserInteractionEnabled = true // 将target改为当前ViewController实例self let tap = UITapGestureRecognizer(target: self, action: #selector(newAccountLabelTapped(_:))) newAccountLabel.addGestureRecognizer(tap) newAccountLabel.textColor = .systemGray return newAccountLabel }()
页面跳转响应方法
// 将参数类型修正为UITapGestureRecognizer @objc func newAccountLabelTapped(_ sender: UITapGestureRecognizer){ let goToVc = RegisterViewController() self.present(goToVc, animated: true, completion: nil) }
内容的提问来源于stack exchange,提问作者user15200527
相关产品推荐
相关产品推荐

