Skip to content

Instantly share code, notes, and snippets.

@mickspecial
Last active January 21, 2019 12:14
Show Gist options
  • Save mickspecial/eef1a3bab577549d2a367be20cbb7564 to your computer and use it in GitHub Desktop.
Save mickspecial/eef1a3bab577549d2a367be20cbb7564 to your computer and use it in GitHub Desktop.
Custom Back Button
import UIKit
// Use it...
/*
let bb = CustomBarButton(image: #imageLiteral(resourceName: "leftWhiteChevron"))
bb.addTarget(self, action: #selector(backAction), for: .touchUpInside)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: bb)
*/
class CustomBarButton: UIControl {
private var buttonImageView: UIImageView = {
let logoView = UIImageView()
logoView.contentMode = .scaleAspectFit
logoView.translatesAutoresizingMaskIntoConstraints = false
return logoView
}()
private var mainTitle: UILabel = {
let label = UILabel()
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 17, weight: .regular)
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
convenience init(title: String = "", image: UIImage) {
self.init()
mainTitle.text = title
buttonImageView.image = image.withRenderingMode(.alwaysTemplate)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
addSubview(buttonImageView)
addSubview(mainTitle)
setupLayout()
}
private func setupLayout() {
NSLayoutConstraint.activate([
// self
widthAnchor.constraint(equalToConstant: 75),
heightAnchor.constraint(equalToConstant: 40),
// logo
buttonImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0),
buttonImageView.centerYAnchor.constraint(equalTo: centerYAnchor),
buttonImageView.widthAnchor.constraint(equalToConstant: 25),
buttonImageView.heightAnchor.constraint(equalToConstant: 25),
// label
mainTitle.centerYAnchor.constraint(equalTo: centerYAnchor),
mainTitle.leadingAnchor.constraint(equalTo: buttonImageView.centerXAnchor),
mainTitle.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: 0)
])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment