Observations - iPhone SE (iOS 14.6)
A UIBarButtonItem
with an icon size of say 24x24
ends up being 43x44
in UINavigationBar
.
UIActivityIndicatorView(style: .medium)
has a size of 20x20
.
You can create a container UIView
instance that wraps UIActivityIndicatorView
to provide necessary horizontal padding and supply this container to UIBarButtonItem.customView
.
Code
@IBAction func upload(_ sender: Any) {
let item = sender as! UIBarButtonItem
let containerView = UIView(frame: .zero)
containerView.translatesAutoresizingMaskIntoConstraints = false
let indicatorView = UIActivityIndicatorView(style: .medium)
indicatorView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(indicatorView)
NSLayoutConstraint.activate([
containerView.widthAnchor.constraint(equalToConstant: 43),
containerView.heightAnchor.constraint(equalToConstant: 44),
indicatorView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -8),
indicatorView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
])
item.customView = containerView
indicatorView.startAnimating()
DispatchQueue.global().async {
Thread.sleep(forTimeInterval: 5)
DispatchQueue.main.async {
item.customView = nil
}
}
}
Please note that these size values 43x44
and right padding 8
may change depending on following factors -
- iPhone vs iPad
- Portrait vs Landscape
- Different versions of iOS
You should check this on all iOS versions that you want to support and test again with each new iOS version published going forward.