gpt4 book ai didi

swift - 检查文本字段实时

转载 作者:行者123 更新时间:2023-11-28 09:00:31 25 4
gpt4 key购买 nike

我找到了这个答案 How to check text field input at real time?

这就是我要找的。但是我在实际执行这段代码时遇到了麻烦。此外,我目前的地理位置使谷歌搜索几乎不可能。

如果在前一个文本字段中输入了正确的数字,我希望能够更改下一个文本字段的背景颜色。如果在 textFieldOne 中输入了正确的值,textfieldTwo 背景颜色将变为绿色。如果该值不正确,则什么也不会发生。请帮帮我。我有两个名为 textFieldOne 和 textFieldTwo 的文本字段,代码中没有其他内容。

最佳答案

只需将它弹出到一个空项目的主视图 Controller 中(尝试在模拟器上使用 iphone 6)

import UIKit    

class ViewController: UIViewController {

var txtField:UITextField!
var txtFieldTwo:UITextField!
var rightNumber = 10

override func viewDidLoad() {
super.viewDidLoad()

//txtFieldOne
var txtField = UITextField()
txtField.frame = CGRectMake(100, 100, 200, 40)
txtField.borderStyle = UITextBorderStyle.None
txtField.backgroundColor = UIColor.blueColor()
txtField.layer.cornerRadius = 5
self.view.addSubview(txtField)

//txtFieldTwo
var txtFieldTwo = UITextField()
txtFieldTwo.frame = CGRectMake(100, 150, 200, 40)
txtFieldTwo.borderStyle = UITextBorderStyle.None
txtFieldTwo.backgroundColor = UIColor.blueColor()
txtFieldTwo.layer.cornerRadius = 5
self.view.addSubview(txtFieldTwo)

txtField.addTarget(self, action: "checkForRightNumber", forControlEvents: UIControlEvents.AllEditingEvents)

self.txtField = txtField
self.txtFieldTwo = txtFieldTwo

}

func checkForRightNumber() {
let number:Int? = self.txtField.text.toInt()
if number == rightNumber {
self.txtFieldTwo.backgroundColor = UIColor.greenColor()
} else {
self.txtFieldTwo.backgroundColor = UIColor.blueColor()
}
}

}

编辑:添加带有 IBOutlets 和 IBActions 的版本

请注意,在此示例中,IBAction 在发送事件/编辑更改时连接到 txtFieldOne

此外,请确保您的文本字段边框颜色设置为无。在 Storyboard 中,执行此操作的方法是选择最左侧带有虚线边框的选项。这样您就可以为背景着色。您可以使用 layer.cornerRadius 来设置边框边缘的圆度。

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var txtField: UITextField!
@IBOutlet weak var txtFieldTwo: UITextField!

var rightNumber = 10

override func viewDidLoad() {
super.viewDidLoad()
}

@IBAction func checkForRightNumber(sender: AnyObject) {
let number:Int? = self.txtField.text.toInt()
if number == rightNumber {
self.txtFieldTwo.backgroundColor = UIColor.greenColor()
} else {
self.txtFieldTwo.backgroundColor = UIColor.blueColor()
}

}

}

关于swift - 检查文本字段实时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32110265/

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