Lev Martens
Lev Martens

Reputation: 180

Swift: Calling the same method from two different buttons

enter image description here

When I tap the orangeButtonOne in the left corner of the screen, my collectionView appears, and when I tap the orangeButtonOne again the collectionView disappears. This works fine but now... the collectionView as you can see also holds a lot of buttons and when I press one of them it calls the exact same method as orangeButtonOne that is closeDropDownView. However, when I tap a button in the collectionView the app crashes on line 99.. and I get the following error:

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!")
        })
    }
}

I don't understand how this method works fine when the orangeButtonOne calls it but then when a collectionView button calls this method the frame value is suddenly nil?

Here is how each button calls the closeDropDownView method:

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()
}
}

Upvotes: 0

Views: 80

Answers (1)

Frankenstein
Frankenstein

Reputation: 16341

You're getting a crash because you are creating a new instance of TestViewController in DropDownViewController and calling closeDropDownView method on that particular instance(testVC). In a new instance of TestViewController the @IBOutlet var dropDownView is empty when you just initialize it and hence you get a crash. To avoid the crash you need to pass the same instance of TestViewController to DropDownViewController to call the exact same instance of closeDropDownView to get the same functionality instead of a crash.

Upvotes: 1

Related Questions