添加UI按钮作为子视图无法在按下时调用选择器

时间:2016-02-17 10:04:26

标签: ios swift uibutton uiimage

这是我的代码

                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)

按钮显示并覆盖图像但选择器

  

单击按钮时未调用

。帮助

3 个答案:

答案 0 :(得分:2)

不喜欢

cell.imageView.addSubview(cell.button)

喜欢并试试这个

  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)

然后检查

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

答案 1 :(得分:0)

pressed:表示您正在调用的方法中有一个选择器。

尝试"按下"或者将你的功能改为:

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

答案 2 :(得分:0)

尝试添加:

cell.imageView.userInteractionEnabled = true

UIImageView默认情况下此属性为false

相关问题