如何在Swift中生成按钮事件?

时间:2014-10-11 15:58:03

标签: ios swift

在objective-c中,可能会生成一个按钮事件:

[button sendActionsForControlEvents: UIControlEventTouchUpInside];

如何在Swift中执行此操作?

我控制拖动以创建我的按钮:

@IBAction func button(sender: AnyObject) {
     println("button tapped!")    
}

当我输入self.button时,Xcode的自动完成功能会使其成为:

button(sender: AnyObject)

如果我输入

button.sendActionsForControlEvents(controlEvents:.TouchUpInside)

然后发生编译器警告:

'(AnyObject) - > ()'没有名为'sendActionsForControlEvents'的成员

3 个答案:

答案 0 :(得分:5)

考虑这行代码:

button.sendActionsForControlEvents(.TouchUpInside)

OR

button.sendActionsForControlEvents(controlEvents:.TouchUpInside)

答案 1 :(得分:1)

可悲的是,上面的代码对Swift不起作用。这是我的代码

import UIKit

class TestButtonProgrammicly: UIViewController {

// Label is set to .hidden and turns on when I click the button.

    @IBOutlet weak var Label: UILabel!
    @IBOutlet weak var TurnOnLabel: UIButton! // ADD THIS AND this works. I hope this will help someone else with this problem. 


    override func viewDidLoad() {
        super.viewDidLoad()

        // I am trying to send a Control Event to the Button to turn on the Label. 
       TurnOnLabel.sendActionsForControlEvents(.TouchUpInside)

    }

    @IBAction func TurnOnLabel(sender: UIButton) {
        // When you click on the Button, the label turns on no problem
        Label.hidden = true
    }
}

答案 2 :(得分:0)

您可以添加以下操作:

self.yourButton.addTarget(self, action: "FavAction:event:", forControlEvents: .TouchUpInside)

并告诉你事件或要点:

func FavAction(sender: UIButton, event: UIEvent) {
var touch: UITouch = event.allTouches().anyObject()
var touchPos: CGPoint = touch.locationInView(self.view)}
相关问题