Button won't function

Here's one for the "What-the-****-is-it-now?" department. I have a simple view that has some details about my iOS app that I want to display when a toolbar button is touched. The UIViewController is called "AboutViewController". I put a view controller into a storyboard and set its class to AboutViewController. Here's the toolbar button code in the superview controller that loads it:


let aboutVC = storyboard.instantiateViewController(withIdentifier: "About")
aboutVC.view.frame = CGRect(x: 0.0, y: 0.0, width: 200, height: 300)
self.view.addSubview(aboutVC.view)
aboutVC.view.center = self.view.center


I put a "Dismiss" button into the controller instance in the storyboard and connected it to this code in AboutViewController:


  @IBAction func dismissButton(_ sender: Any) {
    self.view.removeFromSuperview()
    print("Dismiss button touched.")
  }


When I press the toolbar button, the subview is displayed in the centre of the superview, just as I expected. But when I press the Dismiss button in the subview, nothing happens. The message isn't printed either. I've checked and rechecked that the connection between the button and the IBAction is set.


It seems to me I've done this same damned thing many times before and had no problem. What the **** is wrong now?

Replies

Do I miss something here ?


Isn't it aboutVC.view that you want to remove ?


So, I would write

  @IBAction func dismissButton(_ sender: Any) {
    aboutVC.view.removeFromSuperview()
    print("Dismiss button touched.")
  }


In your code, try to print() before remove, just to see what happens. And tell.


Note: you have other threads opened. are the questions solved ?

You are using the main view of AboutViewController, and adding it as a subview of another view controller.

Which is not a usual way in iOS and any code written in AboutViewController might not work as expected.


If you want to make your code more steady, you should better find another way to show your AboutViewController.

I am using a popup for another of the toolbar buttons. It displays a table view as a table of contents. What are some other alternatives?

According to the docs, removeFromSuperview() does this:


<< If the view’s superview is not

nil
, the superview releases the view. >>

You can show view controllers like popup using usual `present(_:animated:completion:)`.

After taking OOPer's advice, I put this code in the superview controller to show the About view:


  let aboutVC = storyboard.instantiateViewController(withIdentifier: "About")
  aboutVC.modalPresentationStyle = .formSheet
  self.present(aboutVC, animated: true)


I attached this action to the button in the AboutViewController:


  @IBAction func doneButton(_ sender: Any) {
  self.dismiss(animated: true, completion: nil)
  }


Now everything works the way I wanted it to. It pays to play by the book!