【发布时间】:2020-10-04 10:02:05
【问题描述】:
我在 viewDidLoad 中设置了一个约束,然后在键盘出现时更改它的常量。 这是初始设置
bottomConstraint = NSLayoutConstraint(item: bottomBar, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)
view.addConstraint(bottomConstraint)
然后我在收到键盘通知时更改常量:
@objc func handleKeyboardNotification(notification: NSNotification){
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
let isKeyboardShowing = notification.name == UIResponder.keyboardWillShowNotification
bottomConstraint?.constant = isKeyboardShowing ? -keyboardHeight : 0
UIView.animate(withDuration:0.1, delay: 0 , options: .curveEaseOut , animations: {
self.view.layoutIfNeeded()
} , completion: {(completed) in
})
}
}
这很有趣,因为我只是更改常量而不添加另一个约束。尽管如此,我还是在控制台中收到了这个警告:
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x282ae4ff0 UIView:0x109f11110.bottom == UIView:0x109f13240.bottom (active)>",
"<NSLayoutConstraint:0x282ae8050 UIView:0x109f11110.bottom == UIView:0x109f13240.bottom - 291 (active)>"
)
这基本上表明我的限制不能很好地协同工作。 我不知道我做错了什么。
编辑: 这是我用来以编程方式添加底栏的代码:
let bottomBar:UIView = {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
在 ViewdidLoad() 中
view.addSubview(bottomBar)
bottomBar.addSubview(fontView)
bottomBar.addSubview(colorPicker)
fontView.pin(to: bottomBar)
colorPicker.pin(to: bottomBar)
func setUpConstraints(){
NSLayoutConstraint.activate([
bottomBar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
bottomBar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
bottomBar.heightAnchor.constraint(equalToConstant: 70),
])
}
【问题讨论】:
-
bottomBar.translatesAutoresizingMaskIntoConstraints是真是假? -
@Sweeper 是假的
-
您是否使用情节提要作为视图?
-
不,都是程序化创建的
-
@Stackgu 我认为@DonMag 指的是
bottomViewConstraint和bottomConstraint是两个不同的变量。
标签: swift anchor nslayoutconstraint