[英]contentInset of the UIScrollView isn't working
當鍵盤出現時,我試圖將內容向上移動。 這是一個簡單的登錄表單的內容。
請注意,這些不是UITextField
。 它只是一個UIViewController
中間的一個小的UITableView
。 我有一個UIScrollView
填充嵌入該表視圖的視圖控制器。
我已經注冊了鍵盤通知UIKeyboardDidShowNotification
和UIKeyboardWillHideNotification
。
在鍵盤出現時觸發的方法中,我實現了這個答案的一個變體,它幾乎做同樣的事情,設置UIEdgeInsets
的bottom
值,用於設置滾動視圖的contentInset
。
func keyboardWasShown(notification: NSNotification) {
var info: NSDictionary = notification.userInfo as NSDictionary
var keyboardSize: CGSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey).CGRectValue().size
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
}
問題是它什么都不做。 我成功獲得了鍵盤的高度,但沒有任何變化。 誰能告訴我為什么以及我應該怎么做來解決這個問題?
謝謝你。
UIEdgeInsets UIEdgeInsetsMake (
CGFloat top,
CGFloat left,
CGFloat bottom,
CGFloat right
);
你正在設置底部。 嘗試設置頂部插圖。 也許負值會有所幫助。
經過一番折騰,終於如願以償。 我所做的是,在viewDidLoad
我注冊了鍵盤通知。 當鍵盤出現時,我將它的框架放入一個變量中,並將登錄表單(它是一個表視圖)的框架放入另一個變量中。
通過使用CGRectIntersection
,當鍵盤與登錄表單重疊並達到其高度時,我得到了相交部分的框架。 然后我簡單地在滾動視圖的setContentOffset
方法中設置它以自動向上移動滾動視圖。 要將其向下移回原始位置,我只需將滾動視圖的contentOffset
屬性再次設置為CGPointZero
。
func registerForKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWasShown(notification: NSNotification) {
var info: NSDictionary = notification.userInfo as NSDictionary
var keyboardFrame: CGRect = info.objectForKey(UIKeyboardFrameEndUserInfoKey).CGRectValue()
var loginFormFrame: CGRect = self.view.convertRect(self.tableView.frame, fromView: nil)
var coveredFrame: CGRect = CGRectIntersection(loginFormFrame, keyboardFrame)
self.scrollView.setContentOffset(CGPointMake(0, coveredFrame.height + 20), animated: true)
}
func keyboardWillBeHidden(notification: NSNotification) {
self.scrollView.contentOffset = CGPointZero
}
ContentInset
表示內容視圖與封閉滾動視圖之間的距離。 您需要做的是更改 origin.y 值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.