Created
May 28, 2025 00:33
-
-
Save yusuke024/eca4abb35bed83f0c83ed967e8e19fe9 to your computer and use it in GitHub Desktop.
[iOS/Swift] Animate adjusting scroll view top inset via UIViewController.additionalSafeAreaInsets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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