Skip to content

Instantly share code, notes, and snippets.

@scottswezey
Created March 3, 2020 05:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottswezey/f491a39421f14ac6eeaa5654a148cc32 to your computer and use it in GitHub Desktop.
Save scottswezey/f491a39421f14ac6eeaa5654a148cc32 to your computer and use it in GitHub Desktop.
Attempting to have more control over placement of title and buttons in a UINavigationItem
class ViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// This seems like a really bad idea...
self.children.first?.navigationItem.titleView = navItemReplacementVIew()
}
func navItemReplacementVIew() -> UIView {
let view = UIView()
let titleLabel = UILabel()
let actionButton = UIButton()
view.widthAnchor.constraint(equalToConstant: 500).isActive = true
titleLabel.text = "Hello world"
actionButton.setTitle("Done", for: .normal)
actionButton.setTitleColor(.blue, for: .normal)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
actionButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(titleLabel)
view.addSubview(actionButton)
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 8),
titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8),
titleLabel.trailingAnchor.constraint(equalTo: actionButton.leadingAnchor, constant: 8),
titleLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -8),
actionButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 8),
actionButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8),
actionButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -8)
])
return view
}
}
@scottswezey
Copy link
Author

Here's what it looks like in the simulator:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment