计算 Swift 中 UITextInput 文本值长度的最佳方法?
Best way to count length of UITextInput text value in Swift?
我有两个 UITextInput 控件,我想计算其中的字符数。
对于上下文,我有两个输入:一个用于电子邮件地址,一个用于密码。我还有一个“登录”按钮。该按钮默认处于非活动状态,但只要在两个输入中都输入了至少一个字符,我就会以编程方式启用该按钮。这是为了防止在用户在两个字段中输入值之前尝试登录。
到目前为止,我使用的是这种方法:
if count(emailInput.text) > 0 && count(passwordInput.text) > 0 {
// Enable button
} else {
// Disable button
}
使用count()
功能是否可以接受?或者,还有更好的方法?我记得在 iOS/Swift.
中检查字符串的长度有一些陷阱
就我个人而言,以下代码过去运行良好。
if (!emailInput.text.isEmpty && !passwordInput.text.isEmpty) {
// enable button
} else {
// disable button
}
if((emailInput.text!.characters.count) > 0 && (passwordInput.text!.characters.count) > 0) {
// Enable button
} else {
// Disable button
}
Swift 4
emailInput.text!.count
Swift 2
self.emailInput.text!.characters.count
但如果您需要做一些更优雅的事情,您可以创建这样的扩展
如今,将 count
直接放在 text
属性 上后,我的猜测是直接使用它而无需扩展名,但如果您想隔离这类东西,请继续! .
extension UITextField {
var count:Int {
get{
return emailInput.text?.count ?? 0
}
}
}
我有两个 UITextInput 控件,我想计算其中的字符数。
对于上下文,我有两个输入:一个用于电子邮件地址,一个用于密码。我还有一个“登录”按钮。该按钮默认处于非活动状态,但只要在两个输入中都输入了至少一个字符,我就会以编程方式启用该按钮。这是为了防止在用户在两个字段中输入值之前尝试登录。
到目前为止,我使用的是这种方法:
if count(emailInput.text) > 0 && count(passwordInput.text) > 0 {
// Enable button
} else {
// Disable button
}
使用count()
功能是否可以接受?或者,还有更好的方法?我记得在 iOS/Swift.
就我个人而言,以下代码过去运行良好。
if (!emailInput.text.isEmpty && !passwordInput.text.isEmpty) {
// enable button
} else {
// disable button
}
if((emailInput.text!.characters.count) > 0 && (passwordInput.text!.characters.count) > 0) {
// Enable button
} else {
// Disable button
}
Swift 4
emailInput.text!.count
Swift 2
self.emailInput.text!.characters.count
但如果您需要做一些更优雅的事情,您可以创建这样的扩展
如今,将 count
直接放在 text
属性 上后,我的猜测是直接使用它而无需扩展名,但如果您想隔离这类东西,请继续! .
extension UITextField {
var count:Int {
get{
return emailInput.text?.count ?? 0
}
}
}