gpt4 book ai didi

swiftui - 使用 SwiftUI 将 InputAccessoryView/View 固定到键盘

转载 作者:行者123 更新时间:2023-12-02 17:55:19 24 4
gpt4 key购买 nike

SwiftUI 中是否有与 InputAccessoryView 相当的东西(或者有任何迹象表明即将到来?)

如果没有,您将如何模拟 InputAccessoryView 的行为(即固定在键盘顶部的 View )?所需的行为类似于 iMessage,其中有一个固定在屏幕底部的 View ,当键盘打开时该 View 会出现动画,并且位于键盘正上方。例如:

键盘关闭:

keyboard closed

键盘打开:

keyboard open

最佳答案

iOS 15.0+

macOS 12.0+、Mac Catalyst 15.0+

ToolbarItemPlacement 在 iOS 15.0+ 中有一个新属性

keyboard

On iOS, keyboard items are above the software keyboard when present, or at the bottom of the screen when a hardware keyboard is attached.On macOS, keyboard items will be placed inside the Touch Bar.https://developer.apple.com

struct LoginForm: View {
@State private var username = ""
@State private var password = ""
var body: some View {
Form {
TextField("Username", text: $username)
SecureField("Password", text: $password)

}
.toolbar(content: {
ToolbarItemGroup(placement: .keyboard, content: {
Text("Left")
Spacer()
Text("Right")
})
})
}
}

<小时/>

iMessage 类似于 iOS 15+ 中的 InputAccessoryView。


struct KeyboardToolbar<ToolbarView: View>: ViewModifier {
private let height: CGFloat
private let toolbarView: ToolbarView

init(height: CGFloat, @ViewBuilder toolbar: () -> ToolbarView) {
self.height = height
self.toolbarView = toolbar()
}

func body(content: Content) -> some View {
ZStack(alignment: .bottom) {
GeometryReader { geometry in
VStack {
content
}
.frame(width: geometry.size.width, height: geometry.size.height - height)
}
toolbarView
.frame(height: self.height)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}


extension View {
func keyboardToolbar<ToolbarView>(height: CGFloat, view: @escaping () -> ToolbarView) -> some View where ToolbarView: View {
modifier(KeyboardToolbar(height: height, toolbar: view))
}
}

并像平常一样使用 .keyboardToolbar View 修饰符。


struct ContentView: View {
@State private var username = ""

var body: some View {
NavigationView{
Text("Keyboar toolbar")
.keyboardToolbar(height: 50) {
HStack {
TextField("Username", text: $username)
}
.border(.secondary, width: 1)
.padding()
}
}
}
}

关于swiftui - 使用 SwiftUI 将 InputAccessoryView/View 固定到键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56941206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com