Swift 中的 IBOutlet 和 IBAction [英] IBOutlet and IBAction in Swift

查看:39
本文介绍了Swift 中的 IBOutlet 和 IBAction的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 IBOutletIBAction 连接到我的按钮变量,从 Interface Builder 到我的视图控制器.如何在 Swift 中向按钮添加操作方法?此代码似乎不起作用.

I connected a IBOutlet and IBAction to my button variable from Interface Builder to my View Controller. How do I add an action method to the button in Swift? This code doesn't seem to work.

@IBOutlet var OK: UIButton!
@IBAction func OK(sender: UIButton){}

我发现的 Objective-C 等效项是:

The Objective-C equivalent I found is:

@interface Controller
{
    IBOutlet id textField; // links to TextField UI object
}

- (IBAction)doAction:(id)sender; // e.g. called when button pushed

推荐答案

当您将按钮附加到 viewController 并使用 ctrl-drag 创建操作 (IBAction) 时,你在 Swift 中创建了一个看起来像这样的方法(如果它没有参数):

When you attach a button to the viewController and create an action (IBAction) using ctrl-drag, you create a method that looks likes this in Swift (if it doesn't have arguments):

@IBAction func buttonAction() {}

在 Objective-C 中,同样的事情看起来像这样:

In Objective-C the same thing will look like this:

- (IBAction)buttonAction {}

所以这意味着 @IBAction func OK(sender: UIButton){} 是一个动作方法.

So that means that @IBAction func OK(sender: UIButton){} is an action method.

如果您想了解 sender 参数,我会推荐 this SO 帖子.

If you want to know about the sender argument, I would recommend this SO post.

对于你想要做的事情,我创建了一个 IBOutlet 和一个 IBAction,这样我就可以用 outlet 变量改变它的属性,并有IBAction 的东西,就像你上面展示的一样:

For what you want to do, I create an IBOutlet and an IBAction, that way I can change its attributes with the outlet variable, and have the action side of things with the IBAction, like what you show above:

@IBOutlet var OK: UIButton!
@IBAction func OK(sender: UIButton){} 

例如,如果我想隐藏按钮,我会将这段代码放在viewDidLoad

For example, if I want to hide the button, I would put this code in the viewDidLoad

OK.hidden = true

该代码中的 OK 是针对 outlet 变量的,如果我想在按下按钮时将You press me"打印到控制台,我会使用以下代码:

The OK in that code is for the outlet variable, if I wanted to print "You pressed me" to the console when the button is pressed, I would use this code:

@IBAction func OK(sender: UIButton){
  println("You pressed me")
}

上面我正在使用操作将你按下了我"打印到控制台.

Above I am using the action to print "You pressed me" to the console.

当 Swift 2.0 发布时,println 将更改为 print.还有你的行动和出口,我建议给他们不同的名字,以便更容易区分这两者,就像这样:

When Swift 2.0 gets released println will get changed to print. Also with you action and outlet, I would suggest giving them differing names, to make it easier to differentiate the two, something like this:

@IBOutlet var okOutlet: UIButton!
@IBAction func okAction(sender: UIButton){} 

此外,在命名变量、常量、函数等时,您应该使用驼峰式大小写.

Along with that, you should use camel case when naming variables, constants, functions, etc.

这篇关于Swift 中的 IBOutlet 和 IBAction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆