如何禁用在 Swift 中的 TextField 中粘贴? [英] How to disable pasting in a TextField in Swift?

查看:103
本文介绍了如何禁用在 Swift 中的 TextField 中粘贴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 numberPadTextField 并且该函数仅在它包含数字时运行.

如果用户在 TextField 中粘贴字母并单击确定",则会导致应用崩溃.

如何禁止在 TextField 中粘贴?

解决方案

我同意

如果你想了解更多关于 canPerformAction 方法的行为,虽然它是一个 Objective-C 版本,但概念是共享的 此处.

I've got a TextField with a numberPad and the function runs only if it contains numbers.

The user will crash the app if they paste letters in the TextField and click OK.

How can I disable pasting in the TextField?

解决方案

I agree with Leonardo Savio Dabus, if I were you I'd use string checking and just give out a warning, it makes things easier. BUT, if disabling paste option is a fancy feature you really want to put into your app, then you need to do more work. I'll provide the steps below.

Step 1: You need to create another class which extends the UITextField. In this example, I made my CustomUITextField.

import Foundation
import UIKit  //Don't forget this

class CustomUITextField: UITextField {
   override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(UIResponderStandardEditActions.paste(_:)) {
            return false
        }
        return super.canPerformAction(action, withSender: sender)
   }
}

Step 2: Wire the storyboard with your ViewController. You need to declare an IBOutlet as in normal case:

@IBOutlet var textFieldA: CustomUITextField?

Wire the circle next to the @IBOutlet to the TextField in the storyboard. THEN, this is important and easy to be ignored:

  • Go to your storyboard
  • Click the target TextField
  • Select Identity Inspector (the 3rd one)
  • Change the class to CustomUITextField

Quick snapshot is provided below.

That's it, hope this works.

Credit:

Main reference

If you want to know more about the behavior of canPerformAction method, though it's an Objective-C version, the concepts are shared here.

这篇关于如何禁用在 Swift 中的 TextField 中粘贴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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