ios – 按下新的以编程方式创建的按钮时如何设置?

前端之家收集整理的这篇文章主要介绍了ios – 按下新的以编程方式创建的按钮时如何设置?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > How to create a button programmatically?                                    22个
我使用以下代码在Swift中以编程方式创建了一个Button:

let image = UIImage(named: "pin") as UIImage?
    let button = UIButton();
    button.setTitle("Add",forState: .Normal)
    button.setTitleColor(UIColor.blueColor(),forState: .Normal)
    button.setImage(image,forState: .Normal)
    button.frame = CGRectMake(15,-50,200,38)
    button.center = CGPointMake(190.0,345.0);// for center
    self.view.addSubview(button)

我有一个单独的函数来尝试使用我的segue与标识符segueOnPin:

@IBAction func segueToCreate(sender: UIButton) {
    // do something
    performSegueWithIdentifier("segueOnPin",sender: nil)
}

但是,我认为新的UI按钮没有正确连接到第二个功能,因为它不起作用.我通常将它连接到StoryBoard上.但是,新按钮不在StoryBoard上,因为它是以编程方式创建的.我怎样才能解决这个问题?

解决方法

您永远不会为按钮设置目标.
代码添加以下行.

button.addTarget(self,action: "segueToCreate:",forControlEvents: UIControlEvents.TouchUpInside)

猜你在找的Xcode相关文章