【问题标题】:Swift: How to remove "+" and country code from suggested phone number autofill in UITextFieldSwift:如何从 UITextField 中建议的电话号码自动填充中删除“+”和国家/地区代码
【发布时间】:2019-05-08 21:36:50
【问题描述】:

当您将 UITextField 的 textContentType 设置为 .telephoneNumber 时,在您使用文本字段时会出现建议的电话号码。

当您点按建议时,文本字段的文本将成为建议的电话号码,开头带有“+1”。但是,我的文本字段有一个下拉菜单供用户选择国家代码,因此我不希望包含“+1”。有没有办法可以检测是否已点按建议并从文本字段中的该文本中删除“+1”?

【问题讨论】:

  • 您应该在文本字段上获得一个“valueChanged”事件。也可以调用shouldChangeCharactersIn 委托。

标签: ios swift uitextfield uikit


【解决方案1】:

你可以做这样的事情......


class ViewController: UIViewController {

    @IBOutlet weak var yourTextfield: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        yourTextfield.addTarget(self, action: #selector(textFiedDidChange(_:)), for: .editingChanged)
    }


    @objc func textFiedDidChange(_ sender: Any) {
        let prefix = "+1" // What ever you want may be an array and step thru it
        guard yourTextfield.text!.hasPrefix(prefix) else { return }
        yourTextfield.text  = String(yourTextfield.text!.dropFirst(prefix.count).trimmingCharacters(in: .whitespacesAndNewlines))
    }
}

【讨论】:

    猜你喜欢
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多