MrDank
MrDank

Reputation: 2050

Adding UIbutton as subview fails to call the Selector when pressed

This is my code

                cell.imageView.contentMode = .ScaleAspectFit
                cell.imageView.image = UIImage(named: "dummyImage")
                cell.button.backgroundColor = UIColor.grayColor()
                cell.button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
                cell.button.titleLabel?.font = UIFont.systemFontOfSize(8.0)
                cell.button.setTitle("PRESS HERE", forState: .Normal)
                cell.button.addTarget(self, action: "pressed:", forControlEvents: UIControlEvents.
                cell.imageView.addSubview(cell.button)

The button is getting displayed and is overlaying the image but the Selector

pressed

is not getting called when I click the button. Help.

Upvotes: 0

Views: 401

Answers (3)

LorenzOliveto
LorenzOliveto

Reputation: 7936

Try to add:

cell.imageView.userInteractionEnabled = true

UIImageView has this property to false by default.

Upvotes: 0

Anbu.Karthik
Anbu.Karthik

Reputation: 82759

not like

cell.imageView.addSubview(cell.button)

do like and try this

  cell.imageView.userInteractionEnabled = true
  cell.button.frame=CGRectMake(cell.imageView.frame.origin.x, cell.imageView.frame.origin.y, cell.imageView.frame.size.width, cell.imageView.frame.size.height)
 cell.button.tag = indexpath.row
  cell.button.addTarget(self, action: "pressed:", forControlEvents: UIControlEvents. TouchUpInside)
cell.contentview.addSubview(cell.button)

then check like

 func pressed(sender:UIButton)
{
    NSLog("tapped index==%@",sender.tag)
}

Upvotes: 2

Jonas
Jonas

Reputation: 2249

pressed: implies that you have a selector in the method you are calling.

try with "pressed" or change your function to something like:

func pressed(sender:UIButton!)
{
    println("Button tapped")
}

Upvotes: 0

Related Questions