Skip to content

Instantly share code, notes, and snippets.

@sebjvidal
Created February 19, 2026 10:42
Show Gist options
  • Select an option

  • Save sebjvidal/42067ba703fb7c41d767ac410648780f to your computer and use it in GitHub Desktop.

Select an option

Save sebjvidal/42067ba703fb7c41d767ac410648780f to your computer and use it in GitHub Desktop.
UIBarButtonItem Image and Title
import UIKit
extension UIImage {
static func barButtonImage(title titleText: String, showsBadge: Bool) -> UIImage {
let badgeView = UIImageView()
badgeView.image = .badge
badgeView.isHidden = showsBadge == false
badgeView.preferredSymbolConfiguration = UIImage.SymbolConfiguration(textStyle: .footnote)
let titleTextLabel = UILabel()
titleTextLabel.text = titleText
titleTextLabel.font = .preferredFont(forTextStyle: .body, weight: .medium)
let stackView = UIStackView()
stackView.spacing = 6
stackView.axis = .horizontal
stackView.alignment = .center
stackView.addArrangedSubview(badgeView)
stackView.addArrangedSubview(titleTextLabel)
stackView.insetsLayoutMarginsFromSafeArea = false
stackView.isLayoutMarginsRelativeArrangement = true
stackView.layoutMargins = UIEdgeInsets(left: 10, right: 10)
let targetSize = UIView.layoutFittingExpandedSize
stackView.frame.size = stackView.systemLayoutSizeFitting(targetSize)
let image = UIGraphicsImageRenderer(size: stackView.frame.size).image { _ in
stackView.drawHierarchy(in: stackView.bounds, afterScreenUpdates: true)
}
return image
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment