Swift以编程方式将操作添加到视图中

时间:2015-11-24 12:11:49

标签: ios swift

我正在尝试将按钮添加到我添加到主视图的以编程方式创建的视图中。我无法采取行动来处理按钮。这是我到目前为止所尝试的:

itemView = UIImageView(frame:CGRect(x:0, y:0, width:240, height:375))
itemView.backgroundColor = UIColor(red: 255.0/0.0, green: 255.0/0.0, blue: 255.0/0.0, alpha: 0.05)
itemView.contentMode = .Center

buttonConnect = UIButton(frame: CGRect(x:0, y:335, width:120, height:40))
buttonConnect.backgroundColor = UIColor(red: 0.8, green: 0.6, blue: 0.2, alpha: 1.0)
buttonConnect.setTitle("Connect", forState: .Normal)
buttonConnect.tag = 3
buttonConnect.addTarget(itemView, action: "btnConnectTouched:", forControlEvents:.TouchDown)
itemView.addSubview(buttonConnect)

self.addSubview(itemView)

点击按钮的方法如下所示:

func btnConnectTouched(sender:UIButton!)
{
    print("button connect touched")
}

有人可以建议问题是什么吗?谢谢!

6 个答案:

答案 0 :(得分:5)

我不明白为什么要在UIImageView中添加按钮。即使这是你需要的,拿一个UIView,然后把所有其他控件放在里面。您的按钮未单击的原因是您将其放在UIImageView中,而对于UIImageView,userInteractionEnabled的默认值为false。所以你需要启用它,即

 itemView.userInteractionEnabled = true;

同时将按钮目标设置为“self”而不是itemView。

答案 1 :(得分:2)

尝试更改tarjet和事件

buttonConnect.addTarget(itemView, action: "btnConnectTouched:", forControlEvents:.TouchDown)

进入

buttonConnect.addTarget(self, action: "btnConnectTouched:", forControlEvents:. TouchUpInside)

答案 2 :(得分:1)

目标错了:

// buttonConnect.addTarget(itemView, action: "btnConnectTouched:", forControlEvents:.TouchDown)
    // using
    buttonConnect.addTarget(self, action: "btnConnectTouched:", forControlEvents:.TouchDown)
    // or buttonConnect.addTarget(self, action: "btnConnectTouched:", forControlEvents:.TouchUpInside)

答案 3 :(得分:1)

{{1}}

答案 4 :(得分:0)

buttonConnect.addTarget(itemView, action: "btnConnectTouched", forControlEvents:.TouchUpInside)

之后:尝试"btnConnectTouched"

答案 5 :(得分:0)

如果您可以在代码中进行以下两项更改,则可以使用。

  1. 将UIImageView替换为UIView,用于itemView类型和
  2. 用self.view.addSubview(itemView)替换self.addSubview(itemView)
  3. 您的最终代码应该是......

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    
        var itemView = UIView(frame:CGRect(x:0, y:0, width:240, height:375))
        itemView.backgroundColor = UIColor(red: 255.0/0.0, green: 255.0/0.0, blue: 255.0/0.0, alpha: 0.05)
        itemView.contentMode = .Center
    
        var buttonConnect = UIButton(frame: CGRect(x:0, y:335, width:120, height:40))
        buttonConnect.backgroundColor = UIColor(red: 0.8, green: 0.6, blue: 0.2, alpha: 1.0)
        buttonConnect.setTitle("Connect", forState: .Normal)
        buttonConnect.tag = 3
        buttonConnect.addTarget(self, action: "btnConnectTouched:", forControlEvents:.TouchDown)
    
    
        itemView.addSubview(buttonConnect)
    
        self.view.addSubview(itemView)
    
    }
    
    func btnConnectTouched(sender:UIButton!)
    {
        print("button connect touched")
    }
    

    尝试一下......这对我有用......