개발하는 동글 :]

[TIL],[UIKit],[화면의 넓이에 따른 TextField 글자수 제한] 본문

카테고리 없음

[TIL],[UIKit],[화면의 넓이에 따른 TextField 글자수 제한]

동글하다 2023. 9. 27. 00:51

1. Try

    func textFieldDidChangeSelection(_ textField: UITextField) {

        var text = textField.text ?? ""
        let width = textField.frame.width
        if width > (Constant.screenWidth - (Constant.defalutPadding * 2)) {
            text.popLast()
            diaryAddView.titleTextField.text = text
        }
    }
처음 생각해 본 접근으로는 textfield의 넓이를 주지 않은 다음 textfield의 넓이가 글자수에 따라 넓어질 때 그 넓이가 일정한 넓이보다 커질 경우 마지막 글자를 제거한 뒤 텍스트 필드에 재할당 하는 방식이다.

결과는?

위의 동영상과 같이 글자가 사라져 버렸다. 그렇기에 무슨 일이 일어나는지 확인하기 위해 프린트 코드를 추가한 후 콘솔창을 확인해 보았다.

위의 콘솔창의 결과를 보면 알 수 있듯 textField의 넓이가 줄어든 텍스트만큼 작아지지 않아 텍스트가 없어질 때까지 계속하여 반복된다 그렇다면 계속하여 if문을 타지 않도록 넓이를 변경해 주면 되지 않을까라고 생각하여 textField에 넓이를 주었다.
    func textFieldDidChangeSelection(_ textField: UITextField) {

        var text = textField.text ?? ""
        let width = textField.frame.width
        if width > (Constant.screenWidth - (Constant.defalutPadding * 2)) {
            text.popLast()
            print("text\(text),width\(width)")
            diaryAddView.titleTextField.text = text
            let frame = diaryAddView.titleTextField.frame
            diaryAddView.titleTextField.frame = CGRect(x: frame.midX, y: frame.midY, width: 300, height: frame.height)
        }
    }
하지만 넓이는 줄어들지 않았기에 위의 콘솔과 똑같은 콘솔이 출력되었고 텍스트필드는 글자가 없어졌다. 왜 넓이를 제약할 수 없는지 알 수 없었다.

2. 혹시나 해결방법이 필요한 사람들을 위해..

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

        let currentText = textField.text ?? ""
        let newText = (currentText as NSString).replacingCharacters(in: range, with: string)
        let screenWidth = (Constant.screenWidth - (Constant.defalutPadding * 2))
        let maxWidth = Int(screenWidth / textField.font!.pointSize)
        if newText.count <= maxWidth {
            return true
        } else {
            return false
        }
    }

3. 내일의 목표

1. 오늘의 문제 근본적인 해결하기

2. 제네릭, 프로토콜, 이넘 공부해서 활용하기