简体   繁体   中英

Pin TextField to Keyboard in SwiftUI

Is it possible to pin a textfield to the top of the keyboard in SwiftUI? Pretty much identical to the messaging app on iOS where it it is at the bottom of the screen on appear, but moves with the keyboard when you click it, but with SwiftUI, I've looked around and not been able to find anything.

You can achieve this with a toolbar modifier and an toolbaritemgroup with.keyboard placement.

struct ToolBarTest: View {
    @State private var text: String = ""
    @FocusState private var focus: Bool
    @FocusState private var focusToolbar: Bool
    var body: some View {
        ZStack {
            VStack{
                Spacer()
                TextField("toolbar", text: $text)
                    .textFieldStyle(.roundedBorder)
                    .opacity(focus || focusToolbar ? 0 : 1)
                    .focused($focus)
            }
            .toolbar {
                ToolbarItemGroup(placement: .keyboard){
                    TextField("toolbar", text: $text)
                        .textFieldStyle(.roundedBorder)
                        .focused($focusToolbar)
                }
            }
            .onChange(of: focus) {
                if $0{
                    focusToolbar = true
                }
            }
        }
        
    }
}

倒塌

键盘

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM