2015-11-17 79 views
0

單擊文本字段時,我的應用程序向下移動到一個空白區域,然後用鍵盤進行備份。我如何讓它停止這樣做?我只是想讓屏幕在鍵盤激活時稍微向上移動。 此問題與其他Swift鍵盤問題不同,因爲它使用來自Deitel的程序員的書I0S8中的代碼。解決這個問題可能會幫助其他人擁有這本書。 謝謝,Swift鍵盤動畫上下移動

override func viewWillAppear(animated: Bool) { 
    super.viewWillAppear(animated) 
    NSNotificationCenter.defaultCenter().addObserver(self, 
     selector: "keyboardWillShow:", 
     name: UIKeyboardWillShowNotification, 
     object: nil) 
    NSNotificationCenter.defaultCenter().addObserver(self, 
     selector: "keyboardWillHide:", 
     name: UIKeyboardWillHideNotification, 
     object: nil)  // listen for keyboard show/hide notifications 
} 
override func viewWillDisappear(animated: Bool) { 
    super.viewWillDisappear(animated) 
    NSNotificationCenter.defaultCenter().removeObserver(self, 
     name: UIKeyboardWillShowNotification, object: nil) 
    NSNotificationCenter.defaultCenter().removeObserver(self, 
     name: UIKeyboardWillHideNotification, object: nil)  // unregister for keyboard show/hide notifications 
} 
    // called when app receives UIKeyboardWillShowNotification 
func keyboardWillShow(notification: NSNotification) { 
    let userInfo = notification.userInfo! 
    let frame = userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue! 
    let size = frame.CGRectValue().size // keyboard's size 

    // get duration of keyboard's slide-in animation 
    let animationTime = userInfo[UIKeyboardAnimationDurationUserInfoKey]!.doubleValue 

    // scroll self.tableView so selected UITextField above keyboard 
    UIView.animateWithDuration(animationTime) { 
     var insets = self.tableView.contentInset 
     insets.bottom = size.height 
     self.tableView.contentInset = insets 
     self.tableView.scrollIndicatorInsets = insets 
    } 
} // called when app receives UIKeyboardWillHideNotification 
func keyboardWillHide(notification: NSNotification) { 
    var insets = self.tableView.contentInset 
    insets.bottom = 2 
    self.tableView.contentInset = insets 
    self.tableView.scrollIndicatorInsets = insets 
} 
// hide keyboard if user touches Return key 
func textFieldShouldReturn(textField: UITextField) -> Bool { 
    textField.resignFirstResponder() 
    return true 
} 

回答

0

如果調整contentInset財產,你也應該玩的contentOffset財產和調整,要實現你想要的行爲。不過,我會建議不要使用插圖,而是鼓勵你採取兩條路之一:如果使用自動佈局

1):

如果您在使用自動佈局和你掛鉤的約束作爲IBOutlet,上willShow將約束常數調整爲您需要的任何值。

self.constraint.constant = 2 
self.view.layoutIfNeeded() 

將與沒有動畫進行調整和動畫:

self.constraint.constant = 2 
UIView.animateWithDuration(duration, animations: { 
    self.view.layoutIfNeeded() 
}) 

,然後當willHide被調用時,剛剛設置的約束不斷回爲0(或任何其默認/初始值是和動畫)。如果不使用自動佈局

2):

相反調節的限制,調整要移動,並根據需要動畫視圖的幀位置。

+0

這有點幫助,但我仍然有滾動問題。它不再滾過屏幕變白,但仍然一直滾動到底部,然後滾動回頂部。有什麼辦法可以讓它彈出鍵盤嗎?再次感謝您的幫助。 – Will

+0

我回去了,並改變了偏移量和插入。這是修復它。非常感謝! – Will

+0

抱歉,我從未看到您的第一條評論。儘管如此,很高興它爲你解決。 – barndog