2015-09-30 15 views
0

如果一個textfield打開鍵盤和textfield是tableView的成員,那麼它將能夠滾動tableView來看到最後一個項目,並且鍵盤不會隱藏該項目。tableView與scrollView在鍵盤出現時的行爲

enter image description here

如何? UITableView從UIScrollView繼承。我猜想打開鍵盤會增加內容偏移量?我對嗎?

如果textfield是scrollView的一部分,而不是tableView,則不會出現此效果,並且它的鍵盤可以隱藏定位在scrollView下部的其他控件。

如果我想看到scrollView和tableView一樣的效果,我應該手動設置內容偏移嗎?

enter image description here

+0

嘿Janos也許你也可以在這裏找到更有幫助的答案和見解:http://stackoverflow.com/questions/1126726/how-to-make-a-uitextfield-move-up-when-keyboard-is-present – Jelan

回答

1

是的,你必須設置你的內容手動偏移。

首先您註冊通知

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name:UIKeyboardWillShowNotification, object: nil) 
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name:UIKeyboardWillHideNotification, object: nil) 

然後在你的觀察方法。

func textFieldShouldReturn(textField: UITextField) -> Bool { 
    textField.resignFirstResponder() 
    return true 
} 

func keyboardWillShow(notification:NSNotification){ 

    var userInfo = notification.userInfo! 
    var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue() 
    keyboardFrame = self.view.convertRect(keyboardFrame, fromView: nil) 

    var contentInset:UIEdgeInsets = self.scrollView.contentInset 
    contentInset.bottom = keyboardFrame.size.height 
    self.scrollView.contentInset = contentInset 
} 

func keyboardWillHide(notification:NSNotification){ 

    var contentInset:UIEdgeInsets = UIEdgeInsetsZero 
    self.scrollView.contentInset = contentInset 
} 
+0

除了設置'contentInset'外,還可以設置'contentSize'嗎?他們是獨立的權利? –

+0

是的,你可以 – Imran