Skip to content

Instantly share code, notes, and snippets.

@yusuke024
Created May 28, 2025 00:33
Show Gist options
  • Save yusuke024/eca4abb35bed83f0c83ed967e8e19fe9 to your computer and use it in GitHub Desktop.
Save yusuke024/eca4abb35bed83f0c83ed967e8e19fe9 to your computer and use it in GitHub Desktop.
[iOS/Swift] Animate adjusting scroll view top inset via UIViewController.additionalSafeAreaInsets
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
textView.contentInsetAdjustmentBehavior = .always
textView.delegate = self
}
var lastContentOffset: CGPoint?
var shouldAddInsets = false
@IBAction func buttonDidTap(_ sender: Any) {
lastContentOffset = self.textView.contentOffset
additionalSafeAreaInsets.top = self.shouldAddInsets ? 100 : 0
shouldAddInsets.toggle()
}
}
extension ViewController: UITextViewDelegate {
func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) {
if let lastContentOffset {
scrollView.setContentOffset(lastContentOffset, animated: false)
UIView.animate(withDuration: 0.2) {
scrollView.contentOffset.y = -scrollView.adjustedContentInset.top
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment