LoginSignup
7
8

More than 5 years have passed since last update.

UITextField でコピーやペーストを禁止にする

Posted at

やりたいこと

TextField をタップしたときに表示されるポップアップから特定の編集アクションを禁止にする

IMG_0020.PNG

UITextField のサブクラスを作成する

CustomTextField.swift
import UIKit

class CustomUITextField: UITextField {

    // コピーとペーストを禁止にする
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(copy(_:)) || action == #selector(paste(_:)) {
            return false
        }
        return true
    }
}

canPerformAction(_:withSender:) が各編集アクションに対する操作を制御しているのでこれを override する。return false をすることで編集アクションが無効になる。
コピーやペーストといった特定のアクションを禁止にする場合は、引数の actionUIResponderStandardEditActions プロトコルの該当のメソッドと同値であるかを判断してやればよい。

実行結果

IMG_0019.PNG

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8