(SwiftUI, MacOS 11.0) 如何在 SecureTextFeild 中检测焦点?
Posted
技术标签:
【中文标题】(SwiftUI, MacOS 11.0) 如何在 SecureTextFeild 中检测焦点?【英文标题】:(SwiftUI, MacOS 11.0) How to detect focus in SecureTextFeild? 【发布时间】:2021-07-22 03:57:42 【问题描述】:我正在使用 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, height: 14)
.padding(.leading, 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的代码吗? 谢谢
【问题讨论】:
【参考方案1】:这样的事情怎么样: (注意 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, height: 14)
.padding(.leading, 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)
【讨论】:
感谢您的回答。但是最低操作系统版本是 11.0,所以这不起作用。你知道如何使用 .focusable 或 focusableValue 吗?以上是关于(SwiftUI, MacOS 11.0) 如何在 SecureTextFeild 中检测焦点?的主要内容,如果未能解决你的问题,请参考以下文章
SwiftUI TextField (MacOS) 的奇怪行为
SwiftUI不借助ScrollViewReader和ScrollViewProxy实现List自动滚动到底部
SwiftUI不借助ScrollViewReader和ScrollViewProxy实现List自动滚动到底部