iosswiftuibuttonsubviews

Buttons are not working after adding as subviews to background image


I have a working login Viewcontroller but when I added a background image the functionality of buttons are not working, there is no syntax error. When I added as just background image every button works fine but when I added buttons as subviews the buttons are not working.

Here is my VC:

import UIKit
import CoreData
import Foundation

@available(iOS 11.0, *)
class ViewController: UIViewController {

    var imageView = UIImageView()

    @IBOutlet weak var signupButton: UIButton!
    @IBOutlet weak var directButton: UIButton!

    @IBOutlet weak var emailText: UITextField!
    @IBOutlet weak var passText: UITextField!

    @IBOutlet weak var loginButton: UIButton!
    @IBAction func loginAction(_ sender: Any) {

            let appDel = UIApplication.shared.delegate as! AppDelegate
            let context = appDel.persistentContainer.viewContext
            var isMatched = false
            let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
            request.returnsObjectsAsFaults = false
            do {
                let results = try! context.fetch(request)
                if(results.count > 0){
                    for result in results as! [NSManagedObject]
                    {
                        if  emailText.text == result.value(forKey: "username") as? String && passText.text == result.value(forKey: "password") as? String {
                            print(emailText.text!, passText.text!)
                           // usernameGlobal = self.emailText.text!
                            let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle : nil)
                            let desController = mainStoryBoard.instantiateViewController(withIdentifier: "AddViewController") as! AddViewController
                            let newFrontViewController = UINavigationController.init(rootViewController:desController)
                            revealViewController().pushFrontViewController(newFrontViewController, animated: true)
                            isMatched = true
                            break
                        }
                    }

                    if !isMatched {
                        let alertController = UIAlertController(title: "Oops!", message: "Incorrect username or password", preferredStyle: .alert)
                        let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                        alertController.addAction(defaultAction)
                        present(alertController, animated: true, completion: nil)
                    }
                }
            }
    }



    @IBAction func directAction(_ sender: Any) {


        let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle : nil)
        let desController = mainStoryBoard.instantiateViewController(withIdentifier: "AddViewController") as! AddViewController
        let newFrontViewController = UINavigationController.init(rootViewController:desController)
        revealViewController().pushFrontViewController(newFrontViewController, animated: true)


    }



    @IBAction func signupSegue(_ sender: Any) {

        let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle : nil)
        let desController = mainStoryBoard.instantiateViewController(withIdentifier: "SignupViewController") as! SignupViewController
        let newFrontViewController = UINavigationController.init(rootViewController:desController)
        revealViewController().pushFrontViewController(newFrontViewController, animated: true)
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        imageView = UIImageView(frame: UIScreen.main.bounds)
        imageView.image = #imageLiteral(resourceName: "dsplash")
        imageView.contentMode = .scaleAspectFill
         imageView.alpha = 0.5

        self.view.addSubview(imageView)

        self.imageView.addSubview(emailText)
        self.imageView.addSubview(passText)
        self.imageView.addSubview(loginButton)
        self.imageView.addSubview(signupButton)
        self.imageView.addSubview(directButton)

        loginButton.backgroundColor = UIColor.blue
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Solution

  • Don't add buttons as subviews of the imageView, they are laid out by the storyboards. Rather just change this line of code:

    self.view.addSubview(imageView)
    

    to this:

    self.view.insertSubview(imageView, at: 0)
    

    And then remove the lines of code where you put buttons as subviews of the imageView.

    That will put the image below the buttons, so it will look as you want it, and the buttons will keep working.

    Or even better, add that imageView through storyboards (I like being consistent). To keep it as a background image, just drag the imageView int the View Controller Scene to the top of the subviews, so that it is the first subview of the view - that will make all the rest of the view to appear before it:

    enter image description here

    Alternatively if you have a good reason to keep the buttons as imageView subviews, set imageView.userInteractionEnabled = true to make it work with buttons as subviews of the imageView.