Search code examples
iosswiftuibuttontarget-action

First UIButton fires another UIbutton event of same view


i have create two UIButton in swift and added action programmatically. When i try to click on the first button both button action are fired. But when i click on the second button none of the events are firing.

var btnSort = UIButton(frame: CGRectMake(2, 74, 140, 26))
btnSort.setTitle("SORT", forState: UIControlState.Normal)
btnSort.backgroundColor = UIColor.grayColor()
btnSort.tag=10
btnSort.addTarget(self, action: Selector("showSortTbl:"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btnSort)



var btnFilter = UIButton(frame: CGRectMake(140+16+2, 74, 140, 26))
btnFilter.backgroundColor = UIColor.redColor()
btnFilter.tag=11
btnFilter.setTitle("FILTER", forState: UIControlState.Normal)
btnSort.addTarget(self, action: Selector("showFilterTbl:"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btnFilter)



func showSortTbl(sender: UIButton){
    var btnSendTag :UIButton = sender
    if(btnSendTag.tag == 10){

println("show sort")

    }

}


func showFilterTbl(sender: UIButton){

    var btnSendTag :UIButton = sender
    if(btnSendTag.tag == 11){

        println("show filter")

    }

}

Solution

  • Change this line

    btnSort.addTarget(self, action: Selector("showFilterTbl:"), forControlEvents: UIControlEvents.TouchUpInside)
    

    to

    btnFilter.addTarget(self, action: Selector("showFilterTbl:"), forControlEvents: UIControlEvents.TouchUpInside)