Reputation: 1177
I'm working on an app that needs to use the object UINavigationBar for design reasons. The project is fully created programmatically, nothing is created in the storyboard.
Created a UINavigationBar and two buttons, each button has an action:
My problem is related to "move to the esquero side." I take something like "cut" (as the command + X) on the right and paste the left.
What I have:
My Screen is this:
My swift code is:
import UIKit
class ViewController: UIViewController {
var frameSize: CGSize {
get {
return self.view.frame.size
}
}
let navigationBar = UINavigationBar()
var barButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.frame.size = CGSize(width: frameSize.width, height: 64)
navigationBar.frame.origin = CGPointZero
navigationBar.items?.append(UINavigationItem(title: "NavBar"))
self.view.addSubview(navigationBar)
let button = UIButton(frame: CGRect(origin: CGPoint(x: 0, y: 100), size: CGSize(width: 320, height: 50)))
button.titleLabel!.text = "Touch Me"
button.titleLabel!.tintColor = .blueColor()
button.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "touchMe:"))
button.backgroundColor = .purpleColor()
self.view.addSubview(button)
let button2 = UIButton(frame: CGRect(origin: CGPoint(x: 0, y: 200), size: CGSize(width: 320, height: 50)))
button2.titleLabel!.text = "Touch Me 2"
button2.titleLabel!.tintColor = .blueColor()
button2.backgroundColor = .orangeColor()
button2.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "touchMe2:"))
self.view.addSubview(button2)
}
func action(sender: UIButton) {
print("action")
}
func touchMe(sender:UITapGestureRecognizer) {
barButton = UIBarButtonItem(title: "Right Button", style: .Plain, target: self, action: "action:")
navigationBar.items?.first?.rightBarButtonItems?.append(barButton)
}
func touchMe2(sender:UITapGestureRecognizer) {
navigationBar.items?.first?.leftBarButtonItem = barButton
}
}
My question:
How do I move the UIBarButton on the right side for the left side of the UINavigationBar?
Can someone help me?
Thanks for the answer.
Upvotes: 1
Views: 1085
Reputation: 56
Maybe...
var yourButton:UIBarButtonItem = UIBarButtonItem(title: "Button", style: UIBarButtonItemStyle.Plain,target:self, action:"")
self.navigationItem.leftBarButtonItem = yourButton
Upvotes: 0
Reputation: 3956
You can do following changes when you want to move button from right side to left side
func touchMe2(sender:UITapGestureRecognizer) {
navigationBar.items?.first?.rightBarButtonItems?.removeFirst() // if you want to move first button.
navigationBar.items?.first?.leftBarButtonItem = barButton
}
If you want to move arbitrary number you can use removeAtIndex(index : Int)
.
Hope that helps.
Upvotes: 1