簡體   English   中英

如何在Swift 4中從CollectionView的底部到Input Accessory View的頂部設置約束

[英]How to set constraints from the bottom of a collectionView to the top of Input Accessory View in Swift 4

因此我遇到了一個麻煩,要正確設置我的約束之一。基本上,我正在使用情節提要在屏幕上放置兩個視圖。 一個是UITextView,另一個是collectionView。 CollectionView在UItextView下面。 我希望collectionView的底部約束連接到每次鍵盤出現時都會彈出的Input Accessory View的頂部。 通過這樣做,我實質上是使textview的高度動態化。 有什么辦法可以做到嗎? 這是一張圖片這兩個圓圈是輸入附件視圖的一部分。 我希望將集合視圖(即優先級)連接到輸入附件視圖的頂部。 這是另一張帶有詳細標簽和標記的圖片: 詳細標記請幫助!

您可以使用以下方式以編程方式添加約束:

選項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
}

現在最重要的一點 您的文本視圖必須滿足以下條件:

  1. 必須將其高度約束設置為“小於或等於”以使其收縮。
  2. 在所有視圖中,具有優先權內容都必須具有最高價值。 這使得收縮。
  3. 它的內容抗壓縮性優先級必須低。 這保證了它不會阻止收縮。

單擊文本視圖的高度約束時,這是一個正確的選項卡(帶有標尺的選項卡):

在此處輸入圖片說明

以及在界面構建器中打開文本視圖(再次為“標尺”選項卡)時應該看到的內容:

在此處輸入圖片說明

效果如下所示:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM