问题
In a screen, view-scrollview-contentview, there are a lot of textfields in the contentview so I use a scrollview to make them in one screen.Now the problem is I could not click or type in the textfield because I know the scrollview has covered the contentview. But I want to type in the textfield and be able to scroll the screen as well. I tried to see a lot of answers here but could not figure out the correct solution. Both the scrollview and contentview are user interaction enabled, switch on/off the "delays content touches"/"Cancellable content touches" in scrollview but doesn't work. Appreciate any help.
回答1:
Just create two notifications (once when the keyboard appears and other when it dissapear) on the viewDidLoad :
//Notifications for keyBoard when appears.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillShow), name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillHide), name:UIKeyboardWillHideNotification, object: nil)
then call the function which calculates the padding and make an scroll.
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
}
回答2:
Use TPKeyboardAvoiding for auto manage scroll when click on textfield.
https://github.com/michaeltyson/TPKeyboardAvoiding
Make TPKeyboardAvoidingScrollView object and add textfield into this scrollview so it will work fine.
In storyboard use class name "TPKeyboardAvoidingScrollView" in identity inspector and bind it to work well.
来源:https://stackoverflow.com/questions/38840839/ios-swift-beginner