I was able to solve this issue using @HangarRash's idea with a custom container view and a little bit of constraint math.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let w: CGFloat = 64
let h: CGFloat = 64
let v1 = UIView(frame: CGRectMake(0, 0, w, h))
let v2 = UIView(frame: CGRectMake(0, 0, w, h))
let v3 = UIView(frame: CGRectMake(0, 0, w, h))
let v4 = UIView(frame: CGRectMake(0, 0, w, h))
let v5 = UIView(frame: CGRectMake(0, 0, w, h))
let v6 = UIView(frame: CGRectMake(0, 0, w, h))
v1.backgroundColor = .red
v2.backgroundColor = .green
v3.backgroundColor = .yellow
v4.backgroundColor = .gray
v5.backgroundColor = .cyan
v6.backgroundColor = .purple
let views: [UIView] = [v1, v2, v3, v4, v5, v6]
let gap: CGFloat = 16
let width: CGFloat = 32
let height: CGFloat = 32
let totalWidth: CGFloat = width * CGFloat(views.count) + gap * CGFloat(views.count-1)
let container = UIView(frame: CGRectMake(0, 0, totalWidth, height))
container.widthAnchor.constraint(equalToConstant: totalWidth).isActive = true
for (i, view) in views.enumerated() {
view.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(view)
NSLayoutConstraint.activate([
view.widthAnchor.constraint(equalToConstant: width),
view.heightAnchor.constraint(equalToConstant: height), // match container
view.centerYAnchor.constraint(equalTo: container.centerYAnchor),
view.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: CGFloat(i) * (width + gap))
])
}
let containerItem = UIBarButtonItem(customView: container)
if #available(iOS 26.0, *) {
containerItem.hidesSharedBackground = true
}
navigationItem.rightBarButtonItem = containerItem
}
}
extension UIView {
func anchor(to size: CGSize) {
translatesAutoresizingMaskIntoConstraints = false
let constraints = [
heightAnchor.constraint(equalToConstant: size.height),
widthAnchor.constraint(equalToConstant: size.width)
]
for constraint in constraints {
constraint.priority = UILayoutPriority(rawValue: 1000)
}
NSLayoutConstraint.activate(constraints)
}
}