0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

変換させないTextField

Last updated at Posted at 2025-05-26

入力する際に自動的にスペースを挿入することで変換を防ぐ!!!

sample.swift
import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    // ユーザーが文字を入力または削除するたびに呼ばれるメソッド
    // 返り値:テキストフィールドでの入力/削除の処理を許可するかどうか
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // 現在のテキストを取得
        guard let currentText = textField.text else { return true }

        // バックスペース処理の確認
        if string.isEmpty {
            // 削除の場合はそのまま削除させる
            return true
        }
        
        // Enterキーが押された場合はスペースを追加しない
            if string == "\n" {
                return true
            }

        // 入力後のテキストを生成
        let newText = (currentText as NSString).replacingCharacters(in: range, with: string)
        
        // 最初のスペースを削除
        let trimmedText = newText.replacingOccurrences(of: " ", with: "")
        
        // 文字間にスペースを追加
        let spacedText = trimmedText.map { String($0) }.joined(separator: " ")
        
        // もう一度スペースを取り除く
        let finalText = spacedText.replacingOccurrences(of: " ", with: "")
        
        // テキストフィールドを更新
        textField.text = finalText
        
        // デフォルトの処理をキャンセル
        return false
    }

}


0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?