UIScrollView+Extension.swift 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // UIScrollView+Extension.swift
  3. // Gami
  4. //
  5. // Created by OneeChan on 2026/1/25.
  6. //
  7. import Foundation
  8. import UIKit
  9. private var scrollViewOriginContentInsetKey: UInt8 = 0
  10. extension UIScrollView: LNKeyboardNotify {
  11. private var originContentInset: UIEdgeInsets {
  12. get {
  13. objc_getAssociatedObject(self, &scrollViewOriginContentInsetKey) as? UIEdgeInsets ?? .zero
  14. }
  15. set {
  16. objc_setAssociatedObject(self, &scrollViewOriginContentInsetKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  17. }
  18. }
  19. func adjustKeyoard() {
  20. LNEventDeliver.addObserver(self)
  21. }
  22. func onKeyboardWillShow(curInput: UIView?, keyboardHeight: CGFloat) {
  23. guard let curInput, curInput.isDescendant(of: self) else { return }
  24. originContentInset = contentInset
  25. let offset = 20 + keyboardHeight
  26. let editViewY = curInput.convert(curInput.bounds, to: nil).maxY
  27. let distance = UIScreen.main.bounds.height - editViewY
  28. if distance > offset {
  29. return
  30. }
  31. var remain = offset - distance
  32. let curOffset = contentOffset
  33. let availableOffset = contentSize.height + contentInset.bottom - curOffset.y - bounds.height
  34. if availableOffset > remain {
  35. setContentOffset(.init(x: curOffset.x, y: curOffset.y + remain), animated: true)
  36. return
  37. }
  38. remain = remain - availableOffset
  39. var curInset = contentInset
  40. curInset.bottom += remain
  41. contentInset = curInset
  42. setContentOffset(.init(x: curOffset.x, y: curOffset.y + availableOffset + remain), animated: true)
  43. }
  44. func onKeyboardWillHide(curInput: UIView?) {
  45. guard let curInput, curInput.isDescendant(of: self) else { return }
  46. contentInset = originContentInset
  47. }
  48. }