Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add action to programmatically created uibuttons

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)
    }
}
like image 453
melwyn pawar Avatar asked Sep 17 '26 04:09

melwyn pawar


1 Answers

You may try this.

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

    func showMenu() {
        //your code
    }
}
like image 150
Karthik Kumar Avatar answered Sep 23 '26 21:09

Karthik Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!