这是屏幕的整体布局。该按钮位于滚动视图内,因此当第一个响应者出现时,该按钮将被推送到用户视图。然后在第一个响应者辞职时退回
在第二张图片中,第一个响应者出现时的样子。按钮确实向上移动,但现在文本字段被推离屏幕。如果有一种方法可以让按钮向上移动而不会将文本字段从屏幕上移开,那将是惊人的。
@IBOutlet weak var ScrollView: UIScrollView!
@IBOutlet weak var TextField: UITextField!
@IBOutlet weak var testButton: UIButton!
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
}
}
}
答案 0 :(得分:0)
使用类似这样的内容来改变文本字段框架,
func keyboardWillShow(_ notification: Notification) {
var scrollContentSize = CGSize(width: CGFloat(320), height: CGFloat(345))
self.scrollView.contentSize = scrollContentSize
var info = notification.userInfo!
var kbSize = (info[UIKeyboardFrameBeginUserInfoKey] as! String).cgRect().size
var contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height + 100, 0.0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
var keyboardSize = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! String).cgRect().size
UIView.animate(withDuration: 0.3, animations: {() -> Void in
var f = self.view.frame
f.origin.y = -keyboardSize.height + 50
self.view.frame = f
})
}
func keyboardWillHide(_ notification: Notification) {
UIView.animate(withDuration: 0.3, animations: {() -> Void in
var f = self.view.frame
f.origin.y = 0.0
self.view.frame = f
})
}