Konstantin.Efimenko
Konstantin.Efimenko

Reputation: 1478

UITextField in which method I can track combining two symbols in to one?

For example in Czech language, entering in UITextField combination of "cˇ" will transform in to "č" (Diacritic composition). And it happens outside of

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {}

Is there method in UITextFieldDelegate or other which is calling on symbols combining?

Upvotes: 1

Views: 25

Answers (1)

Kiryl Famin
Kiryl Famin

Reputation: 337

I don't think there's a specific method for your case but you can track it manually:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    private let textField: UITextField = {
        let text = UITextField()
        textField.borderStyle = .roundedRect
        textField.translatesAutoresizingMaskIntoConstraints = false
        return tf
    }()
    
    private var previousText: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        setupTextField()
    }

    private func setupTextField() {
        view.addSubview(textField)
        textField.delegate = self
        textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

        NSLayoutConstraint.activate([
            textField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            textField.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            textField.widthAnchor.constraint(equalToConstant: 250),
            textField.heightAnchor.constraint(equalToConstant: 40)
        ])
    }

    @objc private func textFieldDidChange(_ textField: UITextField) {
        guard let newText = textField.text else { return }
        
        if hasCombinedCharacters(previous: previousText, current: newText) {
            print("Обнаружено объединение символов!")
        }
        
        previousText = newText
    }

    private func hasCombinedCharacters(previous: String, current: String) -> Bool {
        let prevDecomposed = previous.decomposedStringWithCanonicalMapping
        let currDecomposed = current.decomposedStringWithCanonicalMapping
        
        return prevDecomposed.count == currDecomposed.count
    }
}

Upvotes: 0

Related Questions