IT story

최대 길이 UITextField

hot-time 2020. 8. 10. 08:09
반응형

최대 길이 UITextField


swift를 사용하여 UITextField에 입력 할 수있는 최대 문자 수를 설정하는 방법을 시도했을 때 ? , 10 개의 문자를 모두 사용하면 문자도 지울 수 없다는 것을 알았습니다.

내가 할 수있는 유일한 일은 작업을 취소하는 것입니다 (모든 문자를 함께 삭제).

누구든지 키보드를 차단하지 않는 방법을 알고 있습니까 (다른 문자 / 기호 / 숫자를 추가 할 수 없지만 백 스페이스를 사용할 수 있음)?


Swift 5 및 iOS 12 textField(_:shouldChangeCharactersIn:replacementString:)에서 UITextFieldDelegate프로토콜의 일부인 다음 메소드 구현을 시도하십시오 .

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let textFieldText = textField.text,
        let rangeOfTextToReplace = Range(range, in: textFieldText) else {
            return false
    }
    let substringToReplace = textFieldText[rangeOfTextToReplace]
    let count = textFieldText.count - substringToReplace.count + string.count
    return count <= 10
}
  • 이 코드의 가장 중요한 부분에서 변환입니다 range( NSRange에) rangeOfTextToReplace( Range<String.Index>). 이 변환이 중요한 이유를 이해하려면 비디오 자습서참조하십시오 .
  • 이 코드가 제대로 작동하도록하려면 textFieldsmartInsertDeleteType도로 설정해야 합니다 UITextSmartInsertDeleteType.no. 이렇게하면 붙여 넣기 작업을 수행 할 때 (원치 않는) 추가 공간이 삽입되는 것을 방지 할 수 있습니다.

어떻게 구현하는 방법을 보여줍니다 아래의 완전한 샘플 코드 textField(_:shouldChangeCharactersIn:replacementString:)A의 UIViewController:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var textField: UITextField! // Link this to a UITextField in Storyboard

    override func viewDidLoad() {
        super.viewDidLoad()

        textField.smartInsertDeleteType = UITextSmartInsertDeleteType.no
        textField.delegate = self
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let textFieldText = textField.text,
            let rangeOfTextToReplace = Range(range, in: textFieldText) else {
                return false
        }
        let substringToReplace = textFieldText[rangeOfTextToReplace]
        let count = textFieldText.count - substringToReplace.count + string.count
        return count <= 10
    }

}

나는 이것을 이렇게한다 :

func checkMaxLength(textField: UITextField!, maxLength: Int) {
    if (countElements(textField.text!) > maxLength) {
        textField.deleteBackward()
    }
}

코드는 나를 위해 작동합니다. 하지만 저는 스토리 보드로 작업합니다. Storyboard에서 변경된 편집시 뷰 컨트롤러의 텍스트 필드에 대한 작업을 추가합니다 .


Swift 4 업데이트

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
     guard let text = textField.text else { return true }
     let newLength = text.count + string.count - range.length
     return newLength <= 10
}

@Martin 답변에서 자세한 내용 추가

// linked your button here
@IBAction func mobileTFChanged(sender: AnyObject) {
    checkMaxLength(sender as! UITextField, maxLength: 10)
}

// linked your button here
@IBAction func citizenTFChanged(sender: AnyObject) {
    checkMaxLength(sender as! UITextField, maxLength: 13)
}

func checkMaxLength(textField: UITextField!, maxLength: Int) {
    // swift 1.0
    //if (count(textField.text!) > maxLength) {
    //    textField.deleteBackward()
    //}
    // swift 2.0
    if (textField.text!.characters.count > maxLength) {
        textField.deleteBackward()
    }
}

Swift 4에서

텍스트 필드 10 자 제한 및 삭제 (백 스페이스) 허용

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField ==  userNameFTF{
            let char = string.cString(using: String.Encoding.utf8)
            let isBackSpace = strcmp(char, "\\b")
            if isBackSpace == -92 {
                return true
            }
            return textField.text!.count <= 9
        }
        return true
    }

func checkMaxLength(textField: UITextField!, maxLength: Int) {
        if (textField.text!.characters.count > maxLength) {
            textField.deleteBackward()
        }
}

IOS 9의 작은 변화


스위프트 3

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

            let nsString = NSString(string: textField.text!)
            let newText = nsString.replacingCharacters(in: range, with: string)
            return  newText.characters.count <= limitCount
    }

마지막 문자를 덮어 쓰려면 :

let maxLength = 10

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

    if range.location > maxLength - 1 {
        textField.text?.removeLast()
    }

    return true
}

을 사용하여 솔루션을 게시 IBInspectable했으므로 인터페이스 빌더에서 또는 프로그래밍 방식으로 최대 길이 값을 변경할 수 있습니다. 여기에서 확인하세요


이 게시물에 언급 된 UITextField에 대한 실행 취소 버그에주의하십시오. UITextField 의 최대 문자 길이 설정

여기에 신속하게 수정하는 방법이 있습니다.

if(range.length + range.location > count(textField.text)) {
        return false;
}

Here is my version of code. Hope it helps!

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let invalidCharacters = NSCharacterSet(charactersInString: "0123456789").invertedSet

        if let range = string.rangeOfCharacterFromSet(invalidCharacters, options: nil, range:Range<String.Index>(start: string.startIndex, end: string.endIndex))
        {
            return false
        }

        if (count(textField.text) > 10  && range.length == 0)
        {
            self.view.makeToast(message: "Amount entry is limited to ten digits", duration: 0.5, position: HRToastPositionCenter)
            return false
        }
        else
        {

        }

        return true
    }

내 앱 중 하나에서이 프로토콜 / 확장 프로그램을 사용해 왔는데 좀 더 읽기 쉽습니다. 백 스페이스를 인식하고 문자가 백 스페이스 일 때 명시 적으로 알려주는 방식이 마음에 듭니다.

고려해야 할 몇 가지 사항 :

1.이 프로토콜 확장을 구현하는 것은 문자 제한을 지정해야합니다. 이는 일반적으로 ViewController가 될 것이지만, 계산 된 속성으로 문자 제한을 구현하고 다른 것을 반환 할 수 있습니다 (예 : 모델 중 하나의 문자 제한).

2. You will need to call this method inside of your text field's shouldChangeCharactersInRange delegate method. Otherwise you won't be able to block text entry by returning false, etc.

3. You will probably want to allow backspace characters through. That's why I added the extra function to detect backspaces. Your shouldChangeCharacters method can check for this and return 'true' early on so you always allow backspaces.

protocol TextEntryCharacterLimited{
    var characterLimit:Int { get } 
}

extension TextEntryCharacterLimited{

    func charactersInTextField(textField:UITextField, willNotExceedCharacterLimitWithReplacementString string:String, range:NSRange) -> Bool{

        let startingLength = textField.text?.characters.count ?? 0
        let lengthToAdd = string.characters.count
        let lengthToReplace = range.length

        let newLength = startingLength + lengthToAdd - lengthToReplace

        return newLength <= characterLimit

    }

    func stringIsBackspaceWith(string:String, inRange range:NSRange) -> Bool{
        if range.length == 1 && string.characters.count == 0 { return true }
        return false
    }

}

If any of you are interested, I have a Github repo where I've taken some of this character limit behavior and put into an iOS framework. There's a protocol you can implement to get a Twitter-like character limit display that shows you how far you've gone above the character limit.

CharacterLimited Framework on Github


Since delegates are a 1-to-1 relationship and I might want to use it elsewhere for other reasons, I like to restrict textfield length adding this code within their setup:

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        setup()
    }

    required override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    func setup() {

        // your setup...

        setMaxLength()
    }

    let maxLength = 10

    private func setMaxLength() {
            addTarget(self, action: #selector(textfieldChanged(_:)), for: UIControlEvents.editingChanged)
        }

        @objc private func textfieldChanged(_ textField: UITextField) {
            guard let text = text else { return }
            let trimmed = text.characters.prefix(maxLength)
            self.text = String(trimmed)

        }

You can use in swift 5 or swift 4 like image look like bellow enter image description here

  1. Add textField in View Controller
  2. Connect to text to ViewController
  3. add the code in view ViewController

     class ViewController: UIViewController , UITextFieldDelegate {
    
      @IBOutlet weak var txtName: UITextField!
    
      var maxLen:Int = 8;
    
     override func viewDidLoad() {
        super.viewDidLoad()
    
        txtName.delegate = self
       }
    
     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
         if(textField == txtName){
            let currentText = textField.text! + string
            return currentText.count <= maxLen
         }
    
         return true;
       }
    }
    

You can download Full Source form GitHub: https://github.com/enamul95/TextFieldMaxLen


You need to check whether the existing string plus the input is greater than 10.

   func textField(textField: UITextField!,shouldChangeCharactersInRange range: NSRange,    replacementString string: String!) -> Bool {
      NSUInteger newLength = textField.text.length + string.length - range.length;
      return !(newLength > 10)
   }

참고URL : https://stackoverflow.com/questions/25223407/max-length-uitextfield

반응형