![](/img/trans.png)
[英]Moving textfield when keyboard appears is covering up top textfields in (Swift)
[英]Moving a textfield with auto layout constraints when the keyboard appears
我有一個搜索欄文本字段和一個表格視圖(用於Google自動完成),當鍵盤出現時,我想將其向上轉換。 我已成功完成此操作,但是,我收到有關約束的警告/錯誤。 我正在此視圖上通過情節提要使用自動布局,並試圖在顯示/隱藏鍵盤之前/之后禁用/啟用約束,但是仍然出現這些錯誤。 我沒有正確禁用自動布局嗎? 我遵循的是在給這個 SO響應。
override func viewDidLoad() {
...
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil)
...
}
func keyboardWillShow(sender: NSNotification) {
self.pixieLabel.hidden = true
self.searchBar.setTranslatesAutoresizingMaskIntoConstraints(true)
self.startingTableView.setTranslatesAutoresizingMaskIntoConstraints(true)
self.searchBar.frame.origin.y -= 150
self.startingTableView.frame.origin.y -= 150
}
func keyboardWillHide(sender: NSNotification) {
self.pixieLabel.hidden = false
self.searchBar.setTranslatesAutoresizingMaskIntoConstraints(false)
self.startingTableView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.searchBar.frame.origin.y += 150
self.startingTableView.frame.origin.y += 150
}
func keyboardWillShow(sender: NSNotification) {
self.pixieLabel.hidden = true
self.seachBarTopConstraint.constant -= 150
self.searchBar.layoutIfNeeded()
}
func keyboardWillHide(sender: NSNotification) {
self.pixieLabel.hidden = false
self.seachBarTopConstraint.constant += 150
self.searchBar.layoutIfNeeded()
}
我認為不應該調整frame
值,而是應該在Interface Builder中創建對約束的@IBOutlet
引用,然后在要為其設置動畫時更改這些約束的constant
量值,然后調用layoutIfNeeded
。 據我了解,手動更改視圖框架的值和自動布局不會混淆。
另外,除非您以編程方式添加約束,否則我不會setTranslatesAutoresizingMaskIntoConstraints
,在這種情況下,您很有可能只是將其設置為false
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.