【问题标题】:How to segue when a new programmatically created button is pressed? [duplicate]按下以编程方式创建的新按钮时如何进行切换? [复制]
【发布时间】:2015-10-04 04:44:04
【问题描述】:

我使用以下代码在 Swift 中以编程方式创建了一个按钮:

    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)

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

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

但是,我认为新的 UIbutton 没有正确连接到第二个功能,因为它不起作用。我通常将它连接到 StoryBoard 上。但是,新按钮不在 StoryBoard 上,因为它是通过编程方式创建的。我该如何解决这个问题?

【问题讨论】:

    标签: ios xcode swift segue


    【解决方案1】:

    您从不为按钮设置目标。 在您的代码中添加以下行。

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

    【讨论】:

    • Swift 可以推断出UIControlEvents,因此可以更简洁地写成forControlEvents: .TouchUpInside
    【解决方案2】:

    但是,新按钮不在 StoryBoard 上,因为它正在 以编程方式创建。我该如何解决这个问题?

    你需要设置按钮的动作,像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-23
      • 2017-11-02
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多