【问题标题】:Swift: Calling the same method from two different buttonsSwift:从两个不同的按钮调用相同的方法
【发布时间】:2020-06-12 23:31:59
【问题描述】:

当我点击屏幕左角的orangeButtonOne 时,我的collectionView 出现,当我再次点击orangeButtonOne 时,collectionView 消失。这工作正常,但现在......你可以看到的collectionView也有很多按钮,当我按下其中一个按钮时,它调用与orangeButtonOne完全相同的方法,即closeDropDownView。但是,当我点击 collectionView 中的按钮时,应用程序在第 99 行崩溃.. 并收到以下错误:

class TestViewController: UIViewController {
 @IBOutlet weak var dropDownView: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        dropDownView.isHidden = true

    func closeDropDownView() {

        UIView.animate(withDuration: 0.3, delay: 0, options: .curveLinear, animations: {

99          var dropTopFrame = self.dropDownView.frame <THREAD1: FATAL ERROR: UNEXPECTEDLY FOUND NIL WHILE IMPLICITLY UNWRAPPING AN OPTIONAL VALUE
            var dropBottomFrame = self.dropDownView.frame

          dropTopFrame.origin.y += dropBottomFrame.size.height
          dropBottomFrame.origin.y -= dropTopFrame.size.height

          self.dropDownView.frame = dropTopFrame
          self.dropDownView.frame = dropBottomFrame

            UIView.animate(withDuration: 0.5) {
                self.dimView.alpha = 0

            }

        }, completion: { finished in
            self.dropDownView.isHidden = true
          print("dropView closed!")
        })
    }
}

我不明白这个方法在 orangeButtonOne 调用它时如何正常工作,但是当一个 collectionView 按钮调用这个方法时,框架值突然为零?

下面是每个按钮如何调用 closeDropDownView 方法:

class TestViewController: UIViewController {
//viewDidLoad etc

    @IBAction func orangeButtonOneTapped(_ sender: Any) {

        if (dropDownView.isHidden == true ) {

            openDropDownView()
        }
        else { closeDropDownView() }
}
extension DropDownViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

let testVC = TestViewController()


       @objc func CVButtonTapped(sender: UIButton!) {
           print("button tapped")

        testVC.closeDropDownView()
}
}

【问题讨论】:

  • 能分享一下collectonView的cellForItem和didSelectItem的代码吗?

标签: swift uiview uicollectionview uibutton


【解决方案1】:

您遇到了崩溃,因为您在 DropDownViewController 中创建了一个新的 TestViewController 实例并在该特定实例 (testVC) 上调用 closeDropDownView 方法。在TestViewController 的新实例中,当您刚刚初始化它时,@IBOutlet var dropDownView 是空的,因此您会崩溃。为避免崩溃,您需要将TestViewController 的相同实例传递给DropDownViewController 以调用closeDropDownView 的完全相同的实例以获得相同的功能而不是崩溃。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    相关资源
    最近更新 更多