ios - 在 UIView 中从 UIViewController 快速调用组件

标签 ios iphone swift uiview uiviewcontroller

<分区>

我有一个问题,我在 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 中发生有趣的事件(如特定动画结束)时收到通知。

关于ios - 在 UIView 中从 UIViewController 快速调用组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39131547/

相关文章:

ios - 如何使用 getData() 在 Swift 中使用 ObjC PNChart 库绘制折线图?

ios - 如何在 swift 2.0 (iOS) 的单例类中创建全局可访问的结构数据?

iphone - iphone 中的文件选择器

iphone - 如何使用 FFMPEG 在我的 iPhone 应用程序中加入两个视频文件?

string - Swift:预期声明错误将 "Label"设置为字符串变量

iphone - 按住退格键时的 UITextViewDelegate 行为

iphone - 为什么这个简单的设置包没有读取任何东西?

ios - Swift 如何使用带有平移手势的属性动画器

android - 如何在应用程序下载页面上区分 Android 和 iOS

ios - 不同文件中不能有 2 个同名常量吗?