3

I have written a class file to create a topBar for my app, I also add in buttons to the top bar after adding target to the buttons added, the same is not triggered the line menuButton.addTarget(self, action: #selector(showMenu), for: .touchUpInside) does not trigger the function showMenu

I create a TN object(from class TopNav) in the main view file and add it to the view, but the menu button does not trigger the tap

import Foundation
import UIKit

class TopNav{

    var topView: UIView = UIView()
    var menuButton: UIButton = UIButton()

    @objc func showMenu(sender: UIButton!) {
        print("show Menu")
    }

    func position(){

        let bounds = UIScreen.main.bounds
        let width = bounds.size.width
        topView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: width, height: 60.0))
        topView.backgroundColor = UIColor.init(colorLiteralRed: 66/255, green: 74/255, blue: 87/255, alpha: 1.0)
        menuButton = UIButton(frame: CGRect(x: (width-40), y: 20.0, width: 30.0, height: 30.0))
        menuButton.setBackgroundImage( UIImage(named:"menu"), for: .normal)
        menuButton.setTitle("", for: UIControlState.normal)
        menuButton.addTarget(self, action: #selector(showMenu), for: .touchUpInside)
        topView.addSubview(menuButton)
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
melwyn pawar
  • 1,766
  • 2
  • 16
  • 21

1 Answers1

2

You may try this.

class TopNav {
    func position() {
        ...
        menuButton.addTarget(self, action: #selector(TopNav.showMenu), for: .touchUpInside)
        ...
    }

    func showMenu() {
        //your code
    }
}
Karthik Kumar
  • 1,375
  • 1
  • 12
  • 29