2016-11-25 60 views
0

前幾天我發佈了這個,但似乎無法找到可行的解決方案。使用滾動視圖時保留對象

(1)這是屏幕的整體佈局。該按鈕位於滾動視圖內,以便在出現時按鈕將被推送至用戶視圖。然後在第一響應者辭職時退後。我不要想要文本字段移動。我想把它們放在我放置它們的位置。只有按鈕是我想要移動的。

(1)https://i.stack.imgur.com/O8iJy.png

(2)的是什麼樣子出現鍵盤的時候喜歡的結果。它最終將文本字段從視圖中移出。

(2)https://i.stack.imgur.com/VDhdI.png

這是我使用的代碼: @IBOutlet弱VAR滾動型:UIScrollView中!

@IBOutlet weak var TextField: UITextField! 

@IBOutlet weak var testButton: UIButton! 

@IBOutlet weak var testView: UIView! 
func closeKeyboard(){ 
    self.view.endEditing(true) 
} 
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    closeKeyboard() 
} 

    override func viewDidLoad() { 
    super.viewDidLoad() 
    NotificationCenter.default.addObserver(self, selector: #selector(scrollviewtest.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) 

    NotificationCenter.default.addObserver(self, selector: #selector(scrollviewtest.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) 

    } 

func keyboardWillShow(notification: NSNotification) { 

    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { 
     if self.view.frame.origin.y == 0{ 
      self.view.frame.origin.y -= keyboardSize.height 
     } 
    } 

} 

func keyboardWillHide(notification: NSNotification) { 
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { 
     if self.view.frame.origin.y != 0{ 
      self.view.frame.origin.y += keyboardSize.height 
     } 
    } 
+1

你爲什麼要使用一個滾動視圖?爲什麼不只是從按鈕添加一個底部約束到超級視圖,然後在鍵盤通知時爲其設置動畫效果? –

回答

0

keyboardWillShow 

你必須創建NSLayoutConstraint的按鍵底部的滾動視圖底部,然後用這個約束操作

而不是

self.view.frame.origin.y -= keyboardSize.height 

。代碼將如下所示。

@IBOutlet weak var buttonBottomConstraint: NSLayoutConstraint! 
.... 

func keyboardWillShow(notification: NSNotification) { 

    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { 
     if self.view.frame.origin.y == 0 { 
      self.buttonBottomConstraint.constant -= keyboardSize.height 
      self.view.layoutIfNeeded() 
     } 
    } 
} 

func keyboardWillHide(notification: NSNotification) { 
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { 
     if self.view.frame.origin.y != 0 { 
      self.buttonBottomConstraint.constant += keyboardSize.height 
     } 
    } 
} 

約束將看起來lijke這樣的:

enter image description here

相關問題