我有一个问题,我在一个UIViewController类中有一个UIViewController,我想在一个发生在另一个文件中的UIView类中的动画之后启用这个按钮。
class MainViewController: UIViewController {
@IBOutlet weak var nextButton: UIButton!
@IBAction func nextButtonPressed(sender: UIButton) {
nextButton.enable = false
}
}动画完成后,当我试图从nextButton类调用viewController时,会得到以下错误:
EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)
我在将nextButton启用设置为true的行上得到了错误。
class CustomView: UIView {
var vc = MainViewController()
func animationEnded() {
vc.nextButton = true
}
}我不知道我错过了什么,我希望得到一些帮助。谢谢
发布于 2016-08-24 19:38:02
您会遇到一个错误,因为在您的CustomView中您创建了一个新的MainViewController,您没有使用从故事板中初始化的那个。新的MainViewController没有初始化它的任何属性,所以nextButton是零,因此当您尝试访问它时会崩溃。
您要做的是从动画已经结束的视图通知您的控制器,以便控制器可以更新按钮(因为控制器拥有该按钮)。在Cocoa中这样做的标准方法是使用委托模式,如下所示:
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)
}
}在这个实现中,控制器是视图委托,当视图中发生有趣的事件时(比如特定的动画结尾),控制器会得到通知。
发布于 2016-08-24 19:33:49
在您的UIView中设置一个委托,它可以告诉您什么时候应该
protocol CustomViewDelegate {
func pushThatButton()
}在CustomView类中,如下所示:
weak var delegate: CustomViewDelegate?然后
func animationEnded() {
delegate.pushThatButton()
}在UIViewController中
class MainViewController: UIViewController, CustomViewDelegate {并实现委托ofc
func pushThatButton()
nextButton.sendActionsForControlEvents(.TouchUpInside)
}几乎忘记了,在viewController和安装委托中对您的视图做一个输出!在viewDidLoad()中或者什么时候您会发现这是最好的
customViewOutlet.delegate = selfhttps://stackoverflow.com/questions/39131547
复制相似问题