gpt4 book ai didi

ios - 格式化电话号码无法正常工作

转载 作者:行者123 更新时间:2023-11-28 15:56:21 24 4
gpt4 key购买 nike

我正在尝试格式化用户输入的电话号码。我已经实现了这个:

import UIKit

class ViewController: UIViewController {
var phoneNumberTextField : UITextField?
var docController: UIDocumentInteractionController?

override func viewDidLoad() {
super.viewDidLoad()
phoneNumberTextField = UITextField(frame: CGRectMake(10, 150, 100, 50))
phoneNumberTextField?.backgroundColor = UIColor.brownColor()
self.view.addSubview(phoneNumberTextField!)


}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
if (textField == phoneNumberTextField)
{
let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
let components = newString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)

let decimalString = components.joinWithSeparator("") as NSString
let length = decimalString.length
let hasLeadingOne = length > 0 && decimalString.characterAtIndex(0) == (1 as unichar)

if length == 0 || (length > 10 && !hasLeadingOne) || length > 11
{
let newLength = (textField.text! as NSString).length + (string as NSString).length - range.length as Int

return (newLength > 10) ? false : true
}
var index = 0 as Int
let formattedString = NSMutableString()

if hasLeadingOne
{
formattedString.appendString("1 ")
index += 1
}
if (length - index) > 3
{
let areaCode = decimalString.substringWithRange(NSMakeRange(index, 3))
formattedString.appendFormat("(%@)", areaCode)
index += 3
}
if length - index > 3
{
let prefix = decimalString.substringWithRange(NSMakeRange(index, 3))
formattedString.appendFormat("%@-", prefix)
index += 3
}

let remainder = decimalString.substringFromIndex(index)
formattedString.appendString(remainder)
textField.text = formattedString as String
return false
}
else
{
return true
}
}
}

来自 Here .当我运行该应用程序并开始添加数字时,没有任何反应。括号和连字符不会出现。我想将 (197)-444-4444 转换为 1974444444。

这里有什么问题吗?

最佳答案

您似乎没有为您的文本字段设置委托(delegate):

phoneNumberTextField.delegate = self

并且您的 View Controller 似乎不符合 UITextFieldDelegate,例如:

ViewController 类:UIViewController,UITextFieldDelegate {

此外,它永远不会为 nil,因此只需将其更改为 var phoneNumberTextField : UITextField!

关于ios - 格式化电话号码无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41675355/

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