Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save odonckers/c841c00a3c500e1b201492f8df2aefbe to your computer and use it in GitHub Desktop.
Save odonckers/c841c00a3c500e1b201492f8df2aefbe to your computer and use it in GitHub Desktop.
UINavigationBar with subtitle / swift
func setTitle(title: String, titleColor: UIColor, titleSize: Int, subtitle: String, subtitleColor: UIColor, subtitleSize: Int) -> UIView {
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: -5, height: 0))
titleLabel.backgroundColor = UIColor.clear
titleLabel.textColor = titleColor
titleLabel.font = UIFont.boldSystemFont(ofSize: CGFloat(titleSize))
titleLabel.text = title
titleLabel.sizeToFit()
let subtitleLabel = UILabel(frame: CGRect(x: 0, y: 18, width: 0, height: 0))
subtitleLabel.backgroundColor = UIColor.clear
subtitleLabel.textColor = subtitleColor
subtitleLabel.font = UIFont.systemFont(ofSize: CGFloat(subtitleSize))
subtitleLabel.text = subtitle
subtitleLabel.sizeToFit()
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: max(titleLabel.frame.size.width, subtitleLabel.frame.size.width), height: 30))
titleView.addSubview(titleLabel)
titleView.addSubview(subtitleLabel)
let widthDiff = subtitleLabel.frame.size.width - titleLabel.frame.size.width
if widthDiff > 0 {
var frame = titleLabel.frame
frame.origin.x = widthDiff / 2
titleLabel.frame = frame.integral
} else {
var frame = titleLabel.frame
frame.origin.x = abs(widthDiff) / 2
titleLabel.frame = frame.integral
}
return titleView
}
// Use:
self.navigationItem.titleView = setTitle(title: "title", titleColor: UIColor.black, titleSize: 17, subtitle: "subtitle", subtitleColor: UIColor.gray, subtitleSize: 12)
// Source: http://stackoverflow.com/questions/12914004/uinavigationbar-titleview-with-subtitle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment