我有一个内容视图,我想动态跟踪高度。
我已经实现了这个解决方案,但我遇到了这个异常:
致命错误:在 View.body 之外访问状态:文件
我该怎么做才能让键盘高度动态更新我的用户界面
struct ContentView: View {
@State var keyboardHeight: CGFloat = 0
var cancellables: Set<AnyCancellable> = []
init() {
NotificationCenter.default.publisher(for: UIResponder.keyboardWillChangeFrameNotification)
.merge(with: NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification))
.compactMap({ notification in
guard let keyboardFrameValue: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return nil }
let keyboardFrame = keyboardFrameValue.cgRectValue
if keyboardFrame.origin.y == UIScreen.main.bounds.height {
return 0
} else {
return keyboardFrame.height - (UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0)
}
})
.assign(to: \.keyboardHeight, on: self)
.store(in: &cancellables)
}
var body: some View {
VStack{
ZStack(alignment: Alignment.bottom) {
List {
Text("Default text").foregroundColor(Color.red)
}
TextField("Placeholder", text: .constant(""))
.frame(minHeight: 30)
.cornerRadius(8.0)
.padding(10)
.background(Color.blue)
}
Spacer()
.frame(height: keyboardHeight)
}
}
}
Run Code Online (Sandbox Code Playgroud)
错误消息几乎说明了问题所在。但是,尽管您无法访问 body 函数(或从 body 调用的函数)之外的 State 变量,但您可以访问 observable 对象。因此,只需通过@ObservedObject 更改@State 并定义一个小类,就足以使其工作。
请注意,此解决方案是为了保持您的工作流程理念完整无缺。虽然,还有其他方法可以完成同样的事情。
import SwiftUI
import Combine
class Model: ObservableObject {
@Published var keyboardHeight: CGFloat = 0
}
struct ContentView: View {
@ObservedObject var model = Model()
var cancellables: Set<AnyCancellable> = []
init() {
NotificationCenter.default.publisher(for: UIResponder.keyboardWillChangeFrameNotification)
.merge(with: NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification))
.compactMap({ notification in
guard let keyboardFrameValue: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return nil }
let keyboardFrame = keyboardFrameValue.cgRectValue
if keyboardFrame.origin.y == UIScreen.main.bounds.height {
return 0
} else {
return keyboardFrame.height - (UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0)
}
})
.assign(to: \.keyboardHeight, on: model)
.store(in: &cancellables)
}
var body: some View {
VStack{
ZStack(alignment: Alignment.bottom) {
List {
Text("Default text").foregroundColor(Color.red)
}
TextField("Placeholder", text: .constant(""))
.frame(minHeight: 30)
.cornerRadius(8.0)
.padding(10)
.background(Color.blue)
}
Spacer()
.frame(height: model.keyboardHeight)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4085 次 |
| 最近记录: |