我正在将scrolview用于高度为1000的视图,起初我不希望我的scrolView滚动。如果我点击任何textField,那么我希望我的scrollview滚动,如果我返回键盘,那么我不希望我的scrollview滚动。
[当键盘出现时,我可以在此处向上显示文本字段,但是当我返回键盘时,当我不希望视图滚动时,我无法将文本字段返回到其原始位置,
请帮助我输入代码。
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var scrolView: UIScrollView!
@IBOutlet weak var upTFLD: UITextField!
var activeTextField = UITextField()
@IBOutlet weak var downTFLD: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
upTFLD.delegate = self
downTFLD.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(onKeyboardAppear(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(onKeyboardDisappear(_:)), name: UIResponder.keyboardDidHideNotification, object: nil)
}
@objc func onKeyboardAppear(_ notification: NSNotification) {
let info = notification.userInfo!
let rect: CGRect = info[UIResponder.keyboardFrameBeginUserInfoKey] as! CGRect
let kbSize = rect.size
let insets = UIEdgeInsets(top: 0, left: 0, bottom: kbSize.height+20, right: 0)
self.scrolView.contentInset = insets
self.scrolView.scrollIndicatorInsets = insets
var visibleRect: CGRect = self.scrolView.convert(self.scrolView.bounds, to: self.view)
visibleRect.size.height -= rect.size.height;
let inputRect: CGRect = self.activeTextField.convert(self.activeTextField.bounds, to: self.scrolView)
if (visibleRect.contains(inputRect)) {
self.scrolView.scrollRectToVisible(inputRect, animated: true)
}
}
@objc func onKeyboardDisappear(_ notification: NSNotification) {
self.scrolView.contentInset = UIEdgeInsets.zero
self.scrolView.scrollIndicatorInsets = UIEdgeInsets.zero
}
public func textFieldDidBeginEditing(_ textField: UITextField) {
activeTextField = textField
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
activeTextField.resignFirstResponder()
return true
}
}
最初,我不想滚动,如果我返回键盘,我需要将textfield移至其原始位置,并且不再滚动。
仅出现键盘,然后只有我需要滚动。请帮助我输入代码。
在viewWillAppear中
yourScrollview.isScrollEnabled = false
出现键盘后将其设为true
yourScrollview.isScrollEnabled = true
或者,您可以使用IQKeyboard管理器来处理文本字段。签出:IQKeyboardManager
您只需要在隐藏键盘后立即设置ScrollView的contentOffset。
创建变量以存储offsetBeforeShowKeyboard
var offsetBeforeShowKeyboard: CGFloat?
最初加载视图时:
self.scrollView.isScrollEnabled = false
选择任何TextField时:
public func textFieldDidBeginEditing(_ textField: UITextField) {
self.scrollView.isScrollEnabled = true
if (self.offsetBeforeShowKeyboard == nil) {
self.offsetBeforeShowKeyboard = self.scrollView.contentOffset
}
}
隐藏键盘时
@objc func onKeyboardDisappear(_ notification: NSNotification) {
self.scrollView.isScrollEnabled = false
if let offset = self.offsetBeforeShowKeyboard {
self.scrolView.setContentOffset(offset, animated: true)
}
self.offsetBeforeShowKeyboard = nil
}