iOS/Swift:如何检测 UITextField 上的触摸动作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32261226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:25:42  来源:igfitidea点击:

iOS/Swift: how to detect touch action on a UITextField

iosuitextfieldtouch-up-inside

提问by Daniele B

I would like to detect the touch action on a UITextField.

我想检测 UITextField 上的触摸动作。

It seems the "Touch Up Inside" action is not fired by touching inside the textfield.

似乎“Touch Up Inside”动作不是通过触摸文本字段内部来触发的。

回答by Daniele B

It seems "Touch Up Inside" is not enabled for UITextField, but "Touch Down" works.

似乎没有为 启用“Touch Up Inside” UITextField,但“Touch Down”有效。

So the solution is as follows:

所以解决方法如下:

Swift 4.x

斯威夫特 4.x

myTextField.addTarget(self, action: #selector(myTargetFunction), for: .touchDown)
@objc func myTargetFunction(textField: UITextField) {
    print("myTargetFunction")
}

Swift 3.x

斯威夫特 3.x

myTextField.addTarget(self, action: #selector(myTargetFunction), for: UIControlEvents.touchDown)

@objc func myTargetFunction(textField: UITextField) {
    print("myTargetFunction")
}

回答by Jonas Deichelmann

Swift 4 - 5:

斯威夫特 4 - 5:

class ViewController: UIViewController, UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == myTextField {
            print("You edit myTextField")
        }
    }
}

This is a delegate function.

这是一个委托函数。

回答by Loxx

here's Swfit:

这是 Swfit:

and you don't need to use the "touchUpInside" just use the delegate methods like so:

并且您不需要使用“touchUpInside”,只需使用如下委托方法:

Make your View controller a delegate:

使您的视图控制器成为委托:

class ViewController: UIViewController, UITextFieldDelegate{

func textFieldDidBeginEditing(textField: UITextField) -> Bool {
    if textField == myTextField {
        return true // myTextField was touched
    }
}

Here's the other delegate methods:

这是其他委托方法:

protocol UITextFieldDelegate : NSObjectProtocol {

    optional func textFieldShouldBeginEditing(textField: UITextField) -> Bool // return NO to disallow editing.
    optional func textFieldDidBeginEditing(textField: UITextField) // became first responder
    optional func textFieldShouldEndEditing(textField: UITextField) -> Bool // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
    optional func textFieldDidEndEditing(textField: UITextField) // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called

    optional func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool // return NO to not change text

    optional func textFieldShouldClear(textField: UITextField) -> Bool // called when clear button pressed. return NO to ignore (no notifications)
    optional func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
}

from swift docs:

来自快速文档:

struct UIControlEvents : RawOptionSetType {
    init(_ rawValue: UInt)
    init(rawValue: UInt)

    static var TouchDown: UIControlEvents { get } // on all touch downs
    static var TouchDownRepeat: UIControlEvents { get } // on multiple touchdowns (tap count > 1)
    static var TouchDragInside: UIControlEvents { get }
    static var TouchDragOutside: UIControlEvents { get }
    static var TouchDragEnter: UIControlEvents { get }
    static var TouchDragExit: UIControlEvents { get }
    static var TouchUpInside: UIControlEvents { get }
    static var TouchUpOutside: UIControlEvents { get }
    static var TouchCancel: UIControlEvents { get }

    static var ValueChanged: UIControlEvents { get } // sliders, etc.

    static var EditingDidBegin: UIControlEvents { get } // UITextField
    static var EditingChanged: UIControlEvents { get }
    static var EditingDidEnd: UIControlEvents { get }
    static var EditingDidEndOnExit: UIControlEvents { get } // 'return key' ending editing

    static var AllTouchEvents: UIControlEvents { get } // for touch events
    static var AllEditingEvents: UIControlEvents { get } // for UITextField
    static var ApplicationReserved: UIControlEvents { get } // range available for application use
    static var SystemReserved: UIControlEvents { get } // range reserved for internal framework use
    static var AllEvents: UIControlEvents { get }
}

UITextField doesn't respond to "touchUpInside" see to the right side, you'll find it's acceptable control events

UITextField 不响应 "touchUpInside" 看右边,你会发现它是可接受的控制事件

回答by Ibrahim

Update For Swift 3

Swift 3 更新

Here is the code for Swift 3:

这是 Swift 3 的代码:

myTextField.addTarget(self, action: #selector(myTargetFunction), for: .touchDown)

This is the function:

这是函数:

func myTargetFunction() {
    print("It works!")
}

回答by Craig P

I referred to the UIControlEvents documentation from Appleand came up with the following:

我参考了AppleUIControlEvents 文档并提出了以下内容:

First add UITextFieldDelegate to your class then,

首先将 UITextFieldDelegate 添加到您的类中,然后,

textBox.delegate = self
textBox.addTarget(self, action: #selector(TextBoxOn(_:)),for: .editingDidBegin)
textBox.addTarget(self, action: #selector(TextBoxOff(_:)),for: .editingDidEnd)

with the following functions:

具有以下功能:

func TextBoxOff(_ textField: UITextField) {
     code
         }                
}

func TextBox(_ textField: UITextField) {
    code
         }
}

回答by drbobdugan

For Swift 3.1:

对于 Swift 3.1:

1) Create a gesture recognizer:

1)创建一个手势识别器:

let textViewRecognizer = UITapGestureRecognizer()

2) Add a handler to the recognizer:

2) 向识别器添加处理程序:

textViewRecognizer.addTarget(self, action: #selector(tappedTextView(_:))) 

3) Add the recognizer to your text view:

3) 将识别器添加到文本视图中:

textView.addGestureRecognizer(textViewRecognizer)

4) Add the handler to your class:

4) 将处理程序添加到您的类中:

func tappedTextView(_ sender: UITapGestureRecognizer) {
        print("detected tap!")
}

回答by Mountain Man

To make this a little clearer these things need to be in place. I used this to make it so if a user entered something in an app of my own's credit textFieldanything in the debit textFieldis deleted.

为了使这更清楚一些,这些东西需要到位。我用它来做到这一点,所以如果用户在我自己的信用应用程序中输入了一些textField东西,借方中的任何内容都会textField被删除。

  1. UITextFieldDelegateneeds to be declared in the View controller i.e class SecondViewController:
  2. The detector functions func myDebitDetector func myCreditDetectorneed to be in the ViewController class.
  3. put debit.addTarget and credit.addtargetinside view will appear.

  4. @IBOutlet weak var debit: UITextField!and @IBOutlet weak var credit: UITextField!are textfields on the storyboard and connected to the viewController.

    class SecondViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
    
    @IBOutlet weak var credit: UITextField!
    @IBOutlet weak var debit: UITextField!
    
        func myDebitDetector(textfield: UITextField ){
            print("using debit")
            credit.text = ""
    
        }
    
        func myCreditDetector(textfield: UITextField) {
            print("using cedit")
            debit.text = ""
        }
    
        override func viewWillAppear(animated: Bool) {
    
    
    
            debit.addTarget(self, action: "myDebitDetector:", forControlEvents: UIControlEvents.TouchDown)
            credit.addTarget(self, action: "myCreditDetector:", forControlEvents: UIControlEvents.TouchDown)
        ....
    
        }
    }
    
  1. UITextFieldDelegate需要在视图控制器中声明,即类 SecondViewController:
  2. 检测器函数 func myDebitDetector func myCreditDetector需要在 ViewController 类中。
  3. debit.addTarget 和 credit.addtarget放入视图中。

  4. @IBOutlet 弱变量借记:UITextField!@IBOutlet 弱无功信用:UITextField!是故事板上的文本字段并连接到视图控制器。

    class SecondViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
    
    @IBOutlet weak var credit: UITextField!
    @IBOutlet weak var debit: UITextField!
    
        func myDebitDetector(textfield: UITextField ){
            print("using debit")
            credit.text = ""
    
        }
    
        func myCreditDetector(textfield: UITextField) {
            print("using cedit")
            debit.text = ""
        }
    
        override func viewWillAppear(animated: Bool) {
    
    
    
            debit.addTarget(self, action: "myDebitDetector:", forControlEvents: UIControlEvents.TouchDown)
            credit.addTarget(self, action: "myCreditDetector:", forControlEvents: UIControlEvents.TouchDown)
        ....
    
        }
    }
    

回答by Lytic

Set the UITextField delegate to your view controller

将 UITextField 委托设置为您的视图控制器

Obj-C

对象-C

textField.delegate = self;

Swift

迅速

textField.delegate = self

Implement the delegate method

实现委托方法

Obj-c

对象-c

-(void)textField:(UITextField*)textField didBeginEditing {
   // User touched textField
}

Swift

迅速

func textFieldDidBeginEditing(textField: UITextField!) {    //delegate method

}

回答by Matheus Faleiro

Swift 3.0 Version:

斯威夫特 3.0 版本:

textFieldClientName.addTarget(self, action: Selector(("myTargetFunction:")), for: UIControlEvents.touchDown)

回答by Andy

Swift 4.2.

斯威夫特 4.2。

Try .editingDidEndinstead of .touchDownand delegate.

尝试.editingDidEnd而不是.touchDowndelegate

myTextField.addTarget(self, action: #selector(myTargetFunction), for: .editingDidEnd)

@objc func myTargetFunction(textField: UITextField) {
    print("textfield pressed")
}