我有一个问题,我在 UIViewController
类中有一个 UIButton
,我想在 UIView 中发生动画后启用该按钮
另一个文件中的类。
class MainViewController: UIViewController {
@IBOutlet weak var nextButton: UIButton!
@IBAction func nextButtonPressed(sender: UIButton) {
nextButton.enable = false
}
}
当我尝试在动画完成后从 viewController
类调用 nextButton
时,出现此错误:
EXC_BAD_INSTRUCTION(code = EXC_I386_INVOP, subcode = 0x0)
我在将 nextButton enable 设置为 true 的行中收到错误。
class CustomView: UIView {
var vc = MainViewController()
func animationEnded() {
vc.nextButton = true
}
}
我不知道我错过了什么,我会很感激一些帮助。谢谢
您遇到错误是因为在您的 CustomView
中您创建了一个新的 MainViewController
,您没有使用从 Storyboard 中初始化的那个。新的 MainViewController
没有初始化任何属性,因此 nextButton
为 nil,因此当您尝试访问它时会崩溃。
您要做的是从 View 通知您的 Controller 动画已经结束,以便 Controller 可以更新按钮(因为 Controller 拥有按钮)。在 Cocoa 中执行此操作的标准方法是像这样使用委托(delegate)模式:
class MainViewController: UIViewController, CustomViewDelegate
{
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var customView: CustomView!
@IBAction func nextButtonPressed(sender: UIButton) {
self.nextButton.enabled = false
}
override func awakeFromNib() {
super.awakeFromNib()
self.customView.delegate = self
}
func customViewAnimationDidEnd(customView: CustomView) {
self.nextButton.enabled = true
}
}
protocol CustomViewDelegate : class
{
func customViewAnimationDidEnd(customView: CustomView)
}
class CustomView: UIView
{
weak var delegate: CustomViewDelegate? = nil
func animationEnded() {
self.delegate?.customViewAnimationDidEnd(self)
}
}
在此实现中, Controller 是 View 委托(delegate),并在 View 中发生有趣的事件(如特定动画结束)时收到通知。