使用 SnapKit 和 Swift 4 更新底部约束
Updating bottom constraint with SnapKit and Swift 4
这是我的代码。我正在使用 KeyboardHelper 库来管理键盘状态和获取键盘高度,还有 SnapKit。我有一个触发键盘的文本字段。当键盘可见时,我想将蓝色框提升到键盘边界之上,因此它是可见的。到目前为止,我没有这样做。你能帮我看看我的代码吗?
private var keyboardHelper : KeyboardHelper?
let box = UIView()
override func viewDidLoad() {
super.viewDidLoad()
keyboardHelper = KeyboardHelper(delegate: self)
guard let superview = self.view else {
return
}
box.backgroundColor = UIColor.blue
superview.addSubview(box)
box.snp.makeConstraints { make in
make.bottom.equalTo(superview.snp.bottom).offset(-16)
make.width.equalTo(200)
make.centerX.equalTo(superview)
make.height.equalTo(100)
}
}
func keyboardWillAppear(_ info: KeyboardAppearanceInfo) {
UIView.animate(withDuration: TimeInterval(info.animationDuration), delay: 0, options: info.animationOptions, animations: {
self.box.snp.updateConstraints({ make in
make.bottom.equalTo(info.endFrame.size.height).offset(10)
})
self.box.layoutIfNeeded()
}, completion: nil)
}
根据 SnapKit 文档:
if you are only updating the constant value of the constraint you can use the method snp.updateConstraints
您的情况需要使用 snp.remakeConstraints
。此外,您可能应该在 superview
上调用 layoutIfNeeded
。
可选地,您可以摆脱不断变化的约束,只在节目中制作适当的变换动画:
box.transform = CGAffineTransform(translationX: 0.0, y: neededTranslation)
隐藏:
box.transform = .identity
这是我的代码。我正在使用 KeyboardHelper 库来管理键盘状态和获取键盘高度,还有 SnapKit。我有一个触发键盘的文本字段。当键盘可见时,我想将蓝色框提升到键盘边界之上,因此它是可见的。到目前为止,我没有这样做。你能帮我看看我的代码吗?
private var keyboardHelper : KeyboardHelper?
let box = UIView()
override func viewDidLoad() {
super.viewDidLoad()
keyboardHelper = KeyboardHelper(delegate: self)
guard let superview = self.view else {
return
}
box.backgroundColor = UIColor.blue
superview.addSubview(box)
box.snp.makeConstraints { make in
make.bottom.equalTo(superview.snp.bottom).offset(-16)
make.width.equalTo(200)
make.centerX.equalTo(superview)
make.height.equalTo(100)
}
}
func keyboardWillAppear(_ info: KeyboardAppearanceInfo) {
UIView.animate(withDuration: TimeInterval(info.animationDuration), delay: 0, options: info.animationOptions, animations: {
self.box.snp.updateConstraints({ make in
make.bottom.equalTo(info.endFrame.size.height).offset(10)
})
self.box.layoutIfNeeded()
}, completion: nil)
}
根据 SnapKit 文档:
if you are only updating the constant value of the constraint you can use the method snp.updateConstraints
您的情况需要使用 snp.remakeConstraints
。此外,您可能应该在 superview
上调用 layoutIfNeeded
。
可选地,您可以摆脱不断变化的约束,只在节目中制作适当的变换动画:
box.transform = CGAffineTransform(translationX: 0.0, y: neededTranslation)
隐藏:
box.transform = .identity