SwiftUI 显示/关闭键盘
Posted
技术标签:
【中文标题】SwiftUI 显示/关闭键盘【英文标题】:SwiftUI Show/Dismiss Keyboard 【发布时间】:2021-03-12 16:07:37 【问题描述】:下面的这段代码完美地显示和隐藏了TextField键盘,除了这个警告消息在运行代码时一直显示给我,有没有人可以帮助避免这个警告???
import UIKit
import SwiftUI
struct FirstResponderTextFiels: UIViewRepresentable
@Binding var text: String
let placeholder: String
@Binding var showKeyboard: Bool
// Create the coordinator
class Coordinator: NSObject, UITextFieldDelegate
@Binding var text: String
@Binding var showKeyboard: Bool
var becameFirstResponder = false
init(text: Binding<String>, showKeyboard: Binding<Bool>)
self._text = text
self._showKeyboard = showKeyboard
func textFieldDidChangeSelection(_ textField: UITextField)
text = textField.text ?? ""
func makeCoordinator() -> Coordinator
return Coordinator(text: $text, showKeyboard: $showKeyboard)
// Create the textfield
func makeUIView(context: Context) -> some UIView
let textField = UITextField()
textField.delegate = context.coordinator
textField.placeholder = placeholder
return textField
func updateUIView(_ uiView: UIViewType, context: Context)
if context.coordinator.showKeyboard
uiView.becomeFirstResponder()
context.coordinator.showKeyboard = false
警告信息
【问题讨论】:
也许我不了解该组件,但它似乎对我不起作用,所以我怀疑将此作为“答案”,但您可以尝试换行在DispatchQueue.main.async
我做了这个,那个一直隐藏键盘,不允许它显示!
【参考方案1】:
查看代码后,我发现如果我删除这部分代码,它没有任何效果,它可以正常工作
func updateUIView(_ uiView: UIViewType, context: Context)
if context.coordinator.showKeyboard
uiView.becomeFirstResponder()
context.coordinator.showKeyboard = false // <--- Remove it
【讨论】:
以上是关于SwiftUI 显示/关闭键盘的主要内容,如果未能解决你的问题,请参考以下文章