[英]How to set constraints from the bottom of a collectionView to the top of Input Accessory View in Swift 4
您可以使用以下方式以編程方式添加約束:
選項1:
let bottomContraint = NSLayoutConstraint(item: self.collectionView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.textField, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 8.0)
self.view.addConstraint(bottomContraint)
選項2:
使用情節提要,按住Control鍵並將其從文本字段拖到集合視圖,然后單擊垂直間距。 然后,您可以點擊編輯約束,並檢查第一項是textField.Top和第二項是collectionView.Bottom 。 然后可以更改常量,包括使用負數是必需的。
首先,從附件到屏幕底部創建一個約束。
然后將其鏈接到視圖控制器中的IBOutlet:
您必須對顯示和隱藏的鍵盤事件做出反應。 因此,您需要從UIKit注冊有關此的通知。 發生此事件時,您可以動態更改身高。
將此添加到視圖控制器的實現中:
@IBOutlet weak var constraintToChange: NSLayoutConstraint!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
//other methods skipped
@objc func keyboardWillShow(_ notification: Notification) {
guard let userInfo = notification.userInfo else {
return //no info to get keyboard size from
}
guard let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue else {
return //no keyboard size to determine height
}
constraintToChange.constant = keyboardSize.height //+ your desired height above keyboard
}
@objc func keyboardWillHide(_ notification: Notification){
constraintToChange.constant = 0.0 //+ your desired height above bottom of the screen
}
現在最重要的一點 。 您的文本視圖必須滿足以下條件:
單擊文本視圖的高度約束時,這是一個正確的選項卡(帶有標尺的選項卡):
以及在界面構建器中打開文本視圖(再次為“標尺”選項卡)時應該看到的內容:
效果如下所示:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.