如何使scrollview快速滚动到所有iPhone设备中的键盘高度?

问题描述 投票:0回答:1

我已经使用约束条件设计了屏幕,但是如果我在iphone7和iPhone8中运行项目,那么在模拟器中将进入某些视图,这就是为什么我在视图控制器中添加了滚动视图,该视图在iphone7和8中运行良好,但在iphone 11、11pro中运行良好, 11 pro max我不需要滚动,因为我的屏幕设计适合其高度,但是在这里滚动也可以工作。正是我想要的,如果iphone的高度较小,那么设计,那么我只想滚动;如果设计适合iphonesize,则我不需要滚动,请在下面的代码中帮助我。

这是我的代码:

//MARK:- scrollview stuff
@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
    self.scrolView.isScrollEnabled = true

    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.isScrollEnabled = false
   if let offset = self.offsetBeforeShowKeyboard {
        self.scrolView.setContentOffset(offset, animated: true)
    }
    self.offsetBeforeShowKeyboard = nil
}

我只想在textfieldBegining中滚动,这就是为什么在viewdidload中我给出了self.scrolView.isScrollEnabled = false:

  func textFieldDidBeginEditing(_ textField: UITextField) {

    activeTextField = textField
    activeTextField.text = ""

    self.scrolView.isScrollEnabled = true
    if (self.offsetBeforeShowKeyboard == nil) {
        self.offsetBeforeShowKeyboard = self.scrolView.contentOffset
    }
}
ios swift scrollview uikeyboard
1个回答
0
投票
对我来说效果很好,请尝试一下。
© www.soinside.com 2019 - 2024. All rights reserved.