SwiftUI - 如何创建只接受数字的 TextField [英] SwiftUI - How to create TextField that only accepts numbers

查看:45
本文介绍了SwiftUI - 如何创建只接受数字的 TextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 SwiftUI 和 iOS 的新手,我正在尝试创建一个只接受数字的输入字段.

I'm new to SwiftUI and iOS, and I'm trying to create an input field that will only accept numbers.

 TextField("Total number of people", text: $numOfPeople)

TextField 目前允许使用字母字符,我该如何设置才能让用户只能输入数字?

The TextField currently allows alphabetic characters, how do I make it so that the user can only input numbers?

推荐答案

tl;dr

结帐 John M解决方案更好的方法.

一种方法是您可以在 TextField 上设置键盘类型,这将限制人们可以输入的内容.

One way to do it is that you can set the type of keyboard on the TextField which will limit what people can type on.

TextField("Total number of people", text: $numOfPeople)
    .keyboardType(.numberPad)

Apple 的文档可以在此处找到,您可以看到所有支持的键盘类型列表此处.

Apple's documentation can be found here, and you can see a list of all supported keyboard types here.

然而,这种方法只是第一步,不理想作为唯一的解决方案:

However, this method is only a first step and is not ideal as the only solution:

  1. iPad 没有数字键盘,因此此方法不适用于 iPad.
  2. 如果用户使用的是硬件键盘,则此方法将不起作用.
  3. 它不会检查用户输入的内容.用户可以将非数字值复制/粘贴到 TextField 中.

您应该清理输入的数据并确保它是纯数字的.

You should sanitise the data that is entered and make sure that it is purely numeric.

对于执行该结帐的解决方案 John M 的解决方案 如下.他在解释如何清理数据及其工作原理方面做得很好.

For a solution that does that checkout John M's solution below. He does a great job explaining how to sanitise the data and how it works.

这篇关于SwiftUI - 如何创建只接受数字的 TextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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