ProgramingTip

Swift에서 shouldChangeCharactersInRange가 어떻게 작동합니까?

bestdevel 2020. 11. 9. 20:06
반응형

Swift에서 shouldChangeCharactersInRange가 어떻게 작동합니까?


내가 사용하고 shouldChangeCharactersInRange을 즉석 유형의 검색을 사용하는 방법으로.

그러나 문제 가 있습니다. 텍스트 필드가 실제로 업데이트되기 전에 shouldChangeCharactersInRange 가 호출됩니다.

Objective C에서는 아래를 사용 하여이 문제를 해결했습니다.

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];

    return YES;
}

그러나 나는 시도를했습니다.

func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
    let txtAfterUpdate:NSString = self.projectSearchTxtFld.text as NSString
    txtAfterUpdate.stringByReplacingCharactersInRange(range, withString: string)

    self.callMyMethod(txtAfterUpdate)
    return true
}

여전히 호출되기 전에 메서드가 여전히 호출됩니까?


스위프트 4, 스위프트 5

이 방법은 사용하지 않습니다. NSString

// MARK: - UITextFieldDelegate

extension MyViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField,
                   shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
        if let text = textField.text,
           let textRange = Range(range, in: text) {
           let updatedText = text.replacingCharacters(in: textRange,
                                                       with: string)
           myvalidator(text: updatedText)
        }
        return true
    }
}

노트. 보안 텍스트 필드를 사용할 수 있습니다.


stringByReplacingCharactersInRange 새 쿠폰을 반환 다음은 어떻습니까?

func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
    if let text = textField.text as NSString? {
        let txtAfterUpdate = text.replacingCharacters(in: range, with: string)
        self.callMyMethod(txtAfterUpdate)
    }
    return true
}


스위프트 3 및 4

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let textFieldText: NSString = (textField.text ?? "") as NSString
    let txtAfterUpdate = textFieldText.replacingCharacters(in: range, with: string)
    callMyMethod(txtAfterUpdate)

    return true
}

func textFieldShouldClear(_ textField: UITextField) -> Bool {
    callMyMethod("")
    return true
}

스위프트 2.2

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let textFieldText: NSString = textField.text ?? ""
    let txtAfterUpdate = textFieldText.stringByReplacingCharactersInRange(range, withString: string)
    callMyMethod(txtAfterUpdate)

    return true
}

func textFieldShouldClear(textField: UITextField) -> Bool {
    callMyMethod("")
    return true
}

textField.text속성은 선택 사항 이지만 nil로 설정할 수 없습니다. nil로 설정하면에서 빈 문자열로 변경됩니다 UITextField. 위의 코드에서 이것이 nil 인 textFieldText경우 빈 문자열로 설정되는 이유 입니다 textField.text(nil 병합 연산자를 통해 ??).

구현 textFieldShouldClear(_:)은 텍스트 필드의 지우기 버튼이 표시되고 탭되는 경우를 처리합니다.


Swift 3 에서는 다음과 같습니다.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let text: NSString = (textField.text ?? "") as NSString
    let resultString = text.replacingCharacters(in: range, with: string)

    return true
}

스위프트 3


사용자가 입력하거나 붙여 넣은 문자를 사전 처리하려면 다음 솔루션이 참처럼 작동합니다.

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

    let strippedString = <change replacements string so it fits your requirement - strip, trim, etc>

    // replace current content with stripped content
    if let replaceStart = textField.position(from: textField.beginningOfDocument, offset: range.location),
        let replaceEnd = textField.position(from: replaceStart, offset: range.length),
        let textRange = textField.textRange(from: replaceStart, to: replaceEnd) {

        textField.replace(textRange, withText: strippedString)
    }
    return false
}

여기에서 찾기 : https://gist.github.com/Blackjacx/2198d86442ec9b9b05c0801f4e392047


Swift 3.0의 UITextField 구성 요소에서 정확한 텍스트를 얻으려면 다음을 사용했습니다.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
   let enteredTxt = textField.text! + string
   doSomethingWithTxt(enteredTxt) //some custom method
}

참고 URL : https://stackoverflow.com/questions/25621496/how-shouldchangecharactersinrange-works-in-swift

반응형