gpt4 book ai didi

ios - 将 textField 条目限制为设定长度的数字条目

转载 作者:可可西里 更新时间:2023-11-01 01:05:32 25 4
gpt4 key购买 nike

我正在尝试限制 3 个不同的文本字段,以便您只能在其中输入数字,这样您可以输入的位数就会受到限制。

这是我的代码:

import Foundation
import UIKit
import Darwin

class View3on3 : UIViewController, UITextFieldDelegate {


@IBOutlet weak var APTeams: UITextField!
@IBOutlet weak var APRounds: UITextField!
@IBOutlet weak var APBreakers: UITextField!


override func viewDidLoad()
{
super.viewDidLoad()
initializeTextFields()
}


func initializeTextFields()
{
APTeams.delegate = self
APTeams.keyboardType = UIKeyboardType.NumberPad

APRounds.delegate = self
APRounds.keyboardType = UIKeyboardType.NumberPad

APBreakers.delegate = self
APBreakers.keyboardType = UIKeyboardType.NumberPad
}


override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}


@IBAction func userTappedBackground(sender: AnyObject)
{
view.endEditing(true)
}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
if string.characters.count == 0 {
return true
}

let prospectiveText = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: String())

switch textField {
case APTeams:
return prospectiveText.containsOnlyCharactersIn("0123456789") && count(prospectiveText) <= 3

case APRounds:
return prospectiveText.containsOnlyCharactersIn("0123456789") && count(prospectiveText) <= 1

case APBreakers:
return prospectiveText.containsOnlyCharactersIn("0123456789") && count(prospectiveText) <= 3

default:
return true
}

}

}

它在这一行抛出一个错误:

let prospectiveText = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: String())

这么说'字符串?'不可转换为 NSString

我遵循了这个网站上的教程: http://www.globalnerdy.com/2015/04/27/how-to-program-an-ios-text-field-that-takes-only-numeric-input-or-specific-characters-with-a-maximum-length/

我做错了什么?

附言。调用 NumberPad 的代码工作正常。当我删除代码以限制位数时,它工作正常。

最佳答案

或者你可以试一试,创建一个方法并在加载 View 中调用它:

func initializeTextFields({
digitsOnlyTextField.delegate = self
digitsOnlyTextField.keyboardType = UIKeyboardType.ASCIICapable

然后,您可以像这样硬编码您的文本字段:

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

case digitsOnlyTextField:
return prospectiveText.containsOnlyCharactersIn("012346789")

试一试并给我一些反馈,祝你好运!

关于ios - 将 textField 条目限制为设定长度的数字条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31552674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com