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

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

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

似乎 "Touch Up Inside" 操作不会通过触摸文本字段内部触发。

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

Obj-C

textField.delegate = self;

Swift

textField.delegate = self

实现委托方法

Obj-c

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

Swift

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

}

这是 Swfit:

并且您不需要使用 "touchUpInside" 只需像这样使用委托方法:

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

class ViewController: UIViewController, UITextFieldDelegate{

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

这是其他委托方法:

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.
}

来自 swift 文档:

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 不响应 "touchUpInside" 看右边,你会发现它是可接受的控件事件

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

所以解决方法如下:

Swift 4.x

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

Swift 3.x

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

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

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

  1. UITextFieldDelegate 需要在视图控制器中声明,即 class第二ViewController:
  2. 探测器函数 func myDebitDetector func myCreditDetector 需要在 ViewController class.
  3. 输入debit.addTarget和credit.addtarget里面的view就会出现

  4. @IBOutlet weak var debit: UITextField! and @ IBOutlet weak var credit: UITextField! 是故事板上的文本字段并连接到 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)
        ....
    
        }
    }
    

Swift 3.0 版本:

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

Update For Swift 3

这是 Swift 3 的代码:

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

这是函数:

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

对于Swift 3.1:

1) 创建手势识别器:

let textViewRecognizer = UITapGestureRecognizer()

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

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

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

textView.addGestureRecognizer(textViewRecognizer)

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

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

我参考了 UIControlEvents documentation from Apple 并得出以下结论:

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

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

具有以下功能:

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

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

Swift 4 岁及以上:

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

这是一个委托函数。

Swift 4.2。

尝试 .editingDidEnd 而不是 .touchDowndelegate.

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

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

关于xamarin.iOS我好用:

YourTextField.WeakDelegate = this;

[...]

[Export("textFieldDidBeginEditing:")]
public void TextViewChanged(UITextField textField)
{
    if (YourTextField.Equals(textField))
        IsYourTextFileFocused = true;
}