本文介绍了在Swift中,如何检测哪个UIControlEvents触发了该动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有4个UITextField的

I currently have 4 UITextField's

@IBOutlet weak var fNameTextField: UITextField!
@IBOutlet weak var lNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!

我想跟踪他们的各种事件:

and I want to keep track of their various events:

[UIControlEvents.EditingChanged, UIControlEvents.EditingDidBegin, UIControlEvents.EditingDidEnd ]

但是我不想有3个单独的事件处理程序,所以我创建了一个这样的函数.该函数可以很好地告诉我哪个UITextField触发了一个事件,但没有告诉我触发了哪个事件.

but I don't want to have 3 event separate event handlers so I created a single function like this. This function does a great job of telling me which UITextField fired an event but it doesn't tell me which event was triggered.:

fNameTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)
lNameTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)
emailTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)
phoneTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)

func onChangeTextField(sender:UITextField){
    switch(sender){
        case fNameTextField:
            print("First Name")
        case lNameTextField:
            print("Last Name")
        case emailTextField:
            print("E-mail")
        case phoneTextField:
            print("Phone")
        default: break
    }
}

如何打印发件人的姓名和触发的事件的名称(例如:.EditingDidEnd,.EditingDidEnd,.EditingDidEnd)?

How can I print both the name of the sender and the name of the event triggered (ex: .EditingDidEnd, .EditingDidEnd, .EditingDidEnd)?

理想情况下,我不想编写多个事件处理程序,我希望使用一个函数.

Ideally, I do not want to write multiple event handlers, I'd prefer a single function.

类似这样的东西:

func onChangeTextField(sender:UITextField){
    switch(sender.eventTriggerd){
        case UIControlEvents.EditingChanged:
            println("EditingChanged")
        case UIControlEvents.EditingDidBegin:
            println("EditingDidBegin")
        case UIControlEvents.EditingDidEnd:
            println("EditingDidEnd")
        default: break
    }
}

推荐答案

不幸的是,您无法区分是哪个控制事件触发了动作处理程序.这与Swift无关.这只是可可的功能.

Unfortunately, you cannot distinguish what control event triggered an action handler. This has nothing to do with Swift; it's just a feature of Cocoa.

这是一个奇怪的设计决定,但事实就是如此.参见例如我的书,它对此抱怨:

It's a strange design decision, but that's just how it is. See, for example, my book, which complains about it:

这篇关于在Swift中,如何检测哪个UIControlEvents触发了该动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:03