Swiftui-从外部设置了Textfield的焦点
我创建了一个自定义textfield
来显示和编辑我的应用程序中的项目标题。当用户创建一个新项目时,我想将此textfield
自动.onappear
自动关注,因此可以立即输入标题。对于现有项目,TextField
不应集中精力。
这样做的唯一方法是在codexfield
之外保存@State
,如下示例吗?对我来说,似乎有一种更优雅的方法可以实现这一目标,而没有创建另一个@State
。
这是一些简化的示例代码:
struct ContentView: View {
@State var text: String = "Text"
@State var focusOnAppear = false
@State var itemID = ""
var body: some View {
VStack {
Button("+ New item") {
focusOnAppear = true
itemID = "0"
}
Button("Existing item"){
focusOnAppear = false
itemID = "1"
}
Button("Another existing item"){
focusOnAppear = false
itemID = "2"
}
}
CustomTextField($text, focusOnAppear: focusOnAppear)
.frame(width: 200, height: 44)
.id(itemID)
}
}
struct CustomTextField: View {
@Binding private var text: String
@FocusState var isFocused: Bool
var focusOnAppear = false
init(_ text: Binding<String>, focusOnAppear: Bool) {
self._text = text
self.focusOnAppear = focusOnAppear
}
var body: some View {
TextField("", text: $text)
.focused($isFocused)
.foregroundColor(isFocused ? .red : .primary)
.border(Color.gray)
.onAppear {
if focusOnAppear {
DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
isFocused = true
}
}
}
}
}
I have created a custom TextField
to display and edit the title of items in my app. When a user creates a new item I would like to focus this TextField
automatically .onAppear
so the title can be entered immediately. For existing items the TextField
should not be focused.
Is the only way to do this to hold a @State
outside of the CustomTextField
like in the example below? To me it seems there might be a more elegant way to achieve this without creating yet another @State
.
Here's a bit of simplified example code:
struct ContentView: View {
@State var text: String = "Text"
@State var focusOnAppear = false
@State var itemID = ""
var body: some View {
VStack {
Button("+ New item") {
focusOnAppear = true
itemID = "0"
}
Button("Existing item"){
focusOnAppear = false
itemID = "1"
}
Button("Another existing item"){
focusOnAppear = false
itemID = "2"
}
}
CustomTextField($text, focusOnAppear: focusOnAppear)
.frame(width: 200, height: 44)
.id(itemID)
}
}
struct CustomTextField: View {
@Binding private var text: String
@FocusState var isFocused: Bool
var focusOnAppear = false
init(_ text: Binding<String>, focusOnAppear: Bool) {
self._text = text
self.focusOnAppear = focusOnAppear
}
var body: some View {
TextField("", text: $text)
.focused($isFocused)
.foregroundColor(isFocused ? .red : .primary)
.border(Color.gray)
.onAppear {
if focusOnAppear {
DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
isFocused = true
}
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论