创建UITextFieldDelegate以限制Swift中的字符数

时间:2017-12-08 12:14:51

标签: swift xcode delegates uitextfield uitextfielddelegate

我是代表们的新手,我正在尝试使用UITextFieldDelegate。我的目标是将此文本字段中的字符数限制为五个字符,就像我创建一个邮政编码文本字段一样。

我正在使用带有文本字段的现成视图控制器,我创建了一个名为ZipCodeDelegate.swift的委托文件。我已经修改了故事板中的文本字段,以便在用户点击字段时显示数字键盘。这是我的viewController:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

// MARK: Outlets

@IBOutlet weak var zipTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

这是我的委托文件:

import Foundation
import UIKit

class ZipCodeDelegate: NSObject, UITextFieldDelegate {


}

我不知道接下来要做什么。我不确定如何限制文本字段的字符数,以及告诉视图控制器该委托文件是否存在以及它应该控制所述文本字段。

2 个答案:

答案 0 :(得分:1)

将此UITextField代理用于Zipcode和Int限制字符数

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

    if string.rangeOfCharacter(from: NSCharacterSet.decimalDigits.inverted) == nil{
        let len = (textField.text?.characters.count)! + string.characters.count
        if len <= 5 {
            return true
        }
    }
    return false
}

UITextField委托方法,用于检查最大字符数限制。

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
    var oldlength : Int = 0
    if textField.text != nil
    {
        oldlength = (textField.text?.count)!
    }

    let replaceMentLength : Int = string.count
    let rangeLength : Int = range.length

    let newLength : Int = oldlength - rangeLength + replaceMentLength

    return newLength <= charaterLimit || false
}

答案 1 :(得分:0)

快捷键4

public class LimitedUITextField: UITextField, UITextFieldDelegate {
    var maxNumber: Int = 0 {
        didSet {
            self.delegate = self
        }
    }


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