我已经看到了这个问题的潜在重复,但它们似乎都没有最小的可重现示例,并且没有遗漏重要上下文的小代码片段。此外,由于我使用的是 SwiftUI,我不确定许多答案是否适用。
我正在使用 SwiftUI 构建 iOS 键盘扩展。相关代码如下:
import UIKit
import SwiftUI
class KeyboardViewController: UIInputViewController {
override func viewDidLoad() {
super.viewDidLoad()
let keyboardController = UIHostingController(rootView: KeyboardWrapper())
keyboardController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(keyboardController.view)
}
}
struct KeyboardWrapper: View {
var body: some View {
GeometryReader { rect in
Keyboard(rect: rect)
}
}
}
我的键盘扩展的根位于 KeyboardViewController
,它添加了一个 UIHostingController
作为 subview ,它包装了 SwiftUI View 的根,KeyboardWrapper
>。然后,KeyboardWrapper
创建Keyboard
。这是一种设置与系统键盘高度相同的键盘的方法,如下所示:
我的问题是如何更改键盘的高度?我已经看到了有关添加约束的帖子,但它们再次缺乏足够的上下文让我确切地知道将它们放在代码中的位置。
最佳答案
使用 anchor
更容易。
import UIKit
import SwiftUI
class KeyboardViewController: UIInputViewController {
override func viewDidLoad() {
super.viewDidLoad()
let keyboardController = UIHostingController(rootView: KeyboardWrapper())
keyboardController.view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(keyboardController.view)
keyboardController.view.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
keyboardController.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
keyboardController.view.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
keyboardController.view.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true
}
}
struct KeyboardWrapper: View {
var body: some View {
HStack {
Button(" A ") {
print("A")
}
.background(Color.red)
.foregroundColor(.white)
Button(" B ") {
print("B")
}
.background(Color.black)
.foregroundColor(.white)
Button(" C ") {
print("C")
}
.background(Color.red)
.foregroundColor(.white)
Button(" D ") {
print("D")
}
.background(Color.black)
.foregroundColor(.white)
}
}
}
但我可以看到您的自定义键盘嵌入在 GeometryReader
中,这可能会导致自动布局约束无法正常工作。在这种情况下,您可以通过在其他约束下方添加此行来修复高度:
keyboardController.view.heightAnchor.constraint(equalToConstant: 120).isActive = true
关于ios - 更改 iOS SwiftUI 键盘扩展高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72758088/