Please check this example, this will solve your problem.
private let imageView = UIImageView(image: UIImage(named: "Image_icon"))
/// WARNING: Change these constants according to your project's design
private struct Const {
/// Image height/width for Large NavBar state
static let ImageSizeForLargeState: CGFloat = 40
/// Margin from right anchor of safe area to right anchor of Image
static let ImageRightMargin: CGFloat = 16
/// Margin from bottom anchor of NavBar to bottom anchor of Image for Large NavBar state
static let ImageBottomMarginForLargeState: CGFloat = 12
/// Margin from bottom anchor of NavBar to bottom anchor of Image for Small NavBar state
static let ImageBottomMarginForSmallState: CGFloat = 6
/// Image height/width for Small NavBar state
static let ImageSizeForSmallState: CGFloat = 32
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.panGestureRecognizer.translation(in: scrollView).y < 0 {
navigationController?.hidesBarsOnSwipe = true
addNavView(const: Const.ImageSizeForSmallState, bottomAnchor: Const.ImageBottomMarginForSmallState)
} else {
navigationController?.hidesBarsOnSwipe = false
addNavView(const: Const.ImageSizeForSmallState, bottomAnchor: Const.ImageBottomMarginForSmallState)
}
}
func addNavView(const: CGFloat = Const.ImageSizeForLargeState, bottomAnchor: CGFloat = Const.ImageBottomMarginForLargeState) {
guard let navigationBar = self.navigationController?.navigationBar else { return }
navigationBar.addSubview(imageView)
// setup constraints
imageView.layer.cornerRadius = const / 2
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView.rightAnchor.constraint(equalTo: navigationBar.rightAnchor, constant: -Const.ImageRightMargin),
imageView.bottomAnchor.constraint(equalTo: navigationBar.bottomAnchor, constant: -bottomAnchor),
imageView.heightAnchor.constraint(equalToConstant: const),
imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor)
])
UIView.animate(withDuration: 0.4, delay: 0.2, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
self.imageView.layoutIfNeeded()
}, completion: nil)
}
https://i.stack.imgur.com/8QfKC.png