问题描述
我正在使用 SwiftUI 开发一个新的 macOS 应用程序,但不知道如何在 SecureTextFeild 中检测焦点。当我输入或超过一定数量的字符时,我想更改边框的颜色。(不是 12.0 Beta...)TextFeild 运行良好,但 SecureTextFeild 不知道该怎么做。这是我的代码
HStack {
Image(idFocus ? "person_blue" : "person_grey")
.resizable()
.frame(width: 14,height: 14)
.padding(.leading,15)
TextField("id".localString(language),text: $id,onEditingChanged: {(changed) in
idFocus = true
}) {
if id.isEmpty{ idFocus = false }
}
.textFieldStyle(PlainTextFieldStyle())
.onTapGesture {
idFocus = true
}
}
.frame(width: 241,height: 42)
.overlay(RoundedRectangle(cornerRadius: 5).stroke(idFocus ? Color.mainColor() : Color.gray,linewidth: 1))
HStack {
Image(pwFocus ? "lock_blue" : "lock_grey")
.resizable()
.frame(width: 14,15)
SecureField("password".localString(language),text: $password)
.textFieldStyle(PlainTextFieldStyle())
}
.padding(.top,6)
.frame(width: 241,height: 42)
.overlay(RoundedRectangle(cornerRadius: 5).stroke(pwFocus ? Color.mainColor() : Color.gray,linewidth: 1))
和 NSTextField 扩展代码
extension NSTextField {
open override var focusRingType: NSFocusRingType {
get {.none}
set {}
}
}
我可以知道可以像 TextField 一样是 SecureTextField 的代码吗? 谢谢
解决方法
这样的事情怎么样: (注意 onFocus 将在 macos12 中被弃用)
struct ContentView: View {
@State var idFocus = false
@State var pwFocus = false
@State var password = ""
@State var id = ""
var body: some View {
VStack {
HStack {
Image(idFocus ? "person_blue" : "person_grey")
.resizable()
.frame(width: 14,height: 14)
.padding(.leading,15)
TextField("id",text: $id,onEditingChanged: {(changed) in
idFocus = true
}) {
if id.isEmpty{ idFocus = false}
}
.textFieldStyle(PlainTextFieldStyle())
.onTapGesture {
idFocus = true
}
.onFocus{ val in // <---
idFocus = val
pwFocus = !val
}
}
.frame(width: 241,height: 42)
.overlay(RoundedRectangle(cornerRadius: 5).stroke(idFocus ? Color.red : Color.gray,lineWidth: 1))
HStack {
Image(pwFocus ? "lock_blue" : "lock_grey")
.resizable()
.frame(width: 14,15)
SecureField("password",text: $password)
.onFocus{ val in // <---
pwFocus = val
idFocus = !val
}
.border(pwFocus ? Color.red : Color.gray) // <---
.textFieldStyle(PlainTextFieldStyle())
}
.padding(.top,6)
.frame(width: 241,height: 42)
.overlay(RoundedRectangle(cornerRadius: 5).stroke(pwFocus ? Color.red : Color.gray,lineWidth: 1))
}.frame(width: 444,height: 444)
}
}