如何自定义UITextField的数字输入? [英] How to customize numeric input for a UITextField?

查看:132
本文介绍了如何自定义UITextField的数字输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Storyboard中有一个 UITextField (代表小费值),以 $ 0.00 开头。如果用户键入 8 ,我希望textField读取 $ 0.08 。如果用户然后键入 3 ,我希望textField读取 $ 0.83 。如果用户然后键入 5 ,我希望textField读取 $ 8.35 。如何以这种方式将输入更改为 UITextField

I have a UITextField (that represents a tip value) in my Storyboard that starts out as $0.00. If the user types an 8, I want the textField to read $0.08. If the user then types a 3, I want the textField to read $0.83. If the user then types 5, I want the textField to read $8.35. How would I go about changing the input to a UITextField in this manner?

推荐答案

您可以通过以下四个步骤执行此操作:

You can do this with the following four steps:


  1. 使您的viewController成为 UITextFieldDelegate 将其添加到定义。

  2. 添加 IBOutlet 通过 Control 将textField从您的Storyboard中的 UITextField 拖放到您的代码中。称之为 myTextField

  3. viewDidLoad()中,将viewController设置为textField的委托

  4. 实现 textField:shouldChangeCharactersInRange:replacementString:
    获取传入的字符并将其添加到提示,然后使用 String(format:)构造函数来格式化字符串。

  1. Make your viewController a UITextFieldDelegate by adding that to the class definition.
  2. Add an IBOutlet to your textField by Control-dragging from the UITextField in your Storyboard to your code. Call it myTextField.
  3. In viewDidLoad(), set your viewController as the textField’s delegate.
  4. Implement textField:shouldChangeCharactersInRange:replacementString:. Take the incoming character and add it to the tip, and then use the String(format:) constructor to format your string.

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var myTextField: UITextField!

    // Tip value in cents
    var tip: Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        myTextField.delegate = self
        myTextField.text = "$0.00"
    }

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        if let digit = Int(string) {
            tip = tip * 10 + digit
            textField.text = String(format:"$%d.%02d", tip/100, tip%100)
        }
        return false
    }
}


这篇关于如何自定义UITextField的数字输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆