programing

Swift에서 Change 문자InRange는 어떻게 작동합니까?

lastcode 2023. 10. 29. 19:45
반응형

Swift에서 Change 문자InRange는 어떻게 작동합니까?

제가 사용하고 있는 것은 should ChangeCharactersInRange를 온더플라이 형태의 검색을 사용하는 방법입니다.

그러나 문제가 있습니다. 텍스트 필드가 실제로 업데이트되기 전에 ChangeCharactersInRange를 호출해야 합니다.

목표 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.textproperty는 선택 사항이므로 0으로 설정할 수 없습니다.0으로 설정하면 다음 내의 빈 문자열로 변경됩니다.UITextField. 위의 코드에서, 그것이 왜textFieldText다음의 경우 문자열을 빈 상태로 설정합니다.textField.textnil (0 병합 연산자를 통해)??).

구현중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
}

shouldChangeCharactersIn키 누르기마다 호출됩니다.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // get the current text, or use an empty string if that failed
    let currentText = textField.text ?? ""

    // attempt to read the range they are trying to change, or exit if we can't
    guard let stringRange = Range(range, in: currentText) else { return false }

    // add their new text to the existing text
    let updatedText = currentText.replacingCharacters(in: stringRange, with: string)

    // make sure the result is under 16 characters
    return updatedText.count <= 16
}

범위 내의 문자를 변경해야 함

func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool { }

이 기능은 변경이 이루어졌지만 UI가 업데이트되지 않고 선택을 기다리는 경우 호출됩니다.

반환된 벌 값을 살펴봅니다.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
  • 만약 당신이 돌아온다면true- iOS에서 변경사항(텍스트, 캐럿...)을 허용함을 의미합니다.
  • 만약 당신이 돌아온다면false- 당신이 이 모든 것에 책임이 있다는 것을 의미합니다.

스위프트 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

이것은 본질적으로 @Vyacheslav의 대답은 내 자신의 사용 사례를 위해 독립적으로 도착한 것입니다. 만약 양식적 접근이 반향을 일으킬 경우를 대비해서 :-)

func textField(_ textField: UITextField, shouldChangeCharactersIn nsRange: NSRange, replacementString: String) -> Bool {
    let range = Range(nsRange, in: textField.text!)!
    let textWouldBecome =  textField.text!.replacingCharacters(in: range, with: replacementString)
    if textWouldBecome != eventModel.title {
        self.navigationItem.setHidesBackButton(true, animated: true)
    } else {
        self.navigationItem.setHidesBackButton(false, animated: true)
    }
    return true
}

eventModel.title을 변경 사항을 확인하는 모든 항목으로 바꿉니다.

스위프트 13

func textFieldDidChangeSelection(_ textField: UITextField) {
    DispatchQueue.main.async { 
        self.textBinding.wrappedValue = textField.text ?? ""
    }
}

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

반응형