简体   繁体   English

限制设置包中文本字段中的字符数

[英]Limit the number of characters in textfield within settings bundle

I am new to Xcode / Swift and have been following examples online to add a settings bundle to my app.我是 Xcode / Swift 的新手,并且一直在在线关注示例以向我的应用程序添加设置包。

What I am struggling with is how to limit the number of characters a user can enter in a settings text field.我正在努力解决的是如何限制用户可以在设置文本字段中输入的字符数。 The root.plist does not seem to have this as an option and this answer seems to be for a textfield within the app rather than one that is changed in settings. root.plist似乎没有这个选项, 这个答案似乎是针对应用程序中的文本字段,而不是在设置中更改的文本字段。

Please can someone point me in the right direction.请有人指出我正确的方向。

Unfortunately this cannot be done for text entered in the settings bundle.不幸的是,对于在设置包中输入的文本,这无法完成。 You do not have control over this.您对此没有控制权。

You could parse the result within your app when loaded from UserDefaults and make changes then if needed, possibly with an alert to the user.您可以在从UserDefaults加载时解析应用程序中的结果,然后根据需要进行更改,可能会向用户发出警报。

The settings root.plist will let you add footer text below controls, so you could at least provide information for user letting them know the maximum length.设置root.plist将允许您在控件下方添加页脚文本,因此您至少可以为用户提供信息,让他们知道最大长度。

An alternative option would be to use a custom settings page within your app, with a UITextField .另一种选择是在您的应用程序中使用自定义设置页面,并带有UITextField Then use the UITextFieldDelegate method shouldChangeCharactersIn to control text entry length.然后使用UITextFieldDelegate方法shouldChangeCharactersIn来控制文本输入长度。

set delegate of your TextField to self and conform your ViewController to UITextFieldDelegate将您的 TextField 的委托设置为 self 并使您的 ViewController 符合 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  //number of characters 
    }

You need to set the delegate of textField and then you have to implement the method mentioned as below你需要设置 textField 的委托,然后你必须实现下面提到的方法

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
   let text = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) ?? ""
   return text.count <= 10 // your count 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM