如何声明文本字段只能包含整数? [英] How can I declare that a text field can only contain an integer?
本文介绍了如何声明文本字段只能包含整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在swift中,我试图创建一个允许按钮启用的文本字段,但仅当文本字段包含整数时。我怎样才能做到这一点?
解决方案
- 请您的视图控制器
UITextFieldDelegate
通过添加UITextFieldDelegate
来的类声明。 - 添加
IBOutlet中
s代表您的文本字段和按钮。 - 在
viewDidLoad
设置按钮的isEnabled
属性为false
并将self
设置为textField.delegate
。 - 实现
textField:shouldChangeCharactersInRange:replacementString:
方法。每次编辑文本字段时都会调用此方法。在那里,通过调用toInt()
检查当前文本字段是否转换为Int
并启用/禁用按钮根据需要。
以下是代码:
class ViewController:UIViewController,UITextFieldDelegate {
@IBOutlet weak var textField:UITextField!
@IBOutlet弱变量按钮:UIButton!
改写FUNC viewDidLoad中(){
super.viewDidLoad()
button.isEnabled =假
textField.delegate =自
}
func textField(textField:UITextField,shouldChangeCharactersInRange range:NSRange,replacementString string:String) - >布尔{
//找出文本字段将是什么将当前编辑
让后文本=(为的TextField.text NSString的).stringByReplacingCharactersInRange(范围,withString:字符串)
if let intVal = text.toInt(){
//文本字段转换为Int
button.isEnabled = true
} else {
//文本字段不是一个Int
button.isEnabled = false
}
//返回true,因此文本字段将被更改
返回true
}
}
编辑:在Swift 3中启用
属性更改为 isEnabled
。
In swift, I am trying to make a text field that will allow a button to be enabled, but only when the text field contains an integer. How can I do this?
解决方案
- Make your view controller a
UITextFieldDelegate
by addingUITextFieldDelegate
to the class declaration. - Add
IBOutlet
s for your text field and your button. - In
viewDidLoad
set your button'sisEnabled
property tofalse
and setself
as thetextField.delegate
. - Implement
textField:shouldChangeCharactersInRange:replacementString:
method. This method will be called every time your text field is edited. In there, check if the current text field converts to anInt
by callingtoInt()
and enable/disable your button as desired.
Here is the code:
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
button.isEnabled = false
textField.delegate = self
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Find out what the text field will be after adding the current edit
let text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
if let intVal = text.toInt() {
// Text field converted to an Int
button.isEnabled = true
} else {
// Text field is not an Int
button.isEnabled = false
}
// Return true so the text field will be changed
return true
}
}
EDIT: In Swift 3 the enabled
property is changed to isEnabled
.
这篇关于如何声明文本字段只能包含整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文