I am using XCode
I have added a Toolbar to my Navigation Controller. And I want to add Bar Buttons to that toolBar.
In my storyboard, I try control drag 'Bar Button Item' to the tool bar, but that does not work, nothing gets added.
So can 'Bar Button Item' to the tool bar?
Thank you.
Update:
I add my own UINavigationController, bind the toolbar from storyboard to my class as 'mytoolbar'.
And did the answer code in swift,
But when I run it on simulator, I don't see any tool bar item.
class AppNavigationController: UINavigationController {
#IBOutlet weak var mytoolbar: UIToolbar!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var rightButton = UIBarButtonItem(title: "Title", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("method"))
var items = [AnyObject]()
items.append(rightButton)
mytoolbar.items = items
}
func method() {
println("Something cool here")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
For Swift:
let item1 = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action: "touchPickImage")
let item2 = UIBarButtonItem(title: "Delete", style: .Plain, target: self, action: "deleteImage")
toolBar.setItems([item], animated: true)
you can get reference for tool bar either from view controller or you drag it and then add.
You may want to go with a programmatic solution here:
UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithTitle:#"Title 1"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(buttonClick1:)];
UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithTitle:#"Title 1"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(buttonClick2:)];
NSMutableArray *myButtonArray = [[NSArray alloc] initWithObjects:button1, button2, nil];
toolBar.items = myButtonArray;
Try setting your bar button items, then using:
self.setToolbarItems([UIBarButtonItem], animated: false)
Related
When I create a UIBarButton programatically in the viewDidLoad() method it does not show up when I run the program. I am not sure what is happening. Sorry I am new to xcode and do not understand how everything works.
var menuButton: UIBarButtonItem = UIBarButtonItem()
override func viewDidLoad() {
super.viewDidLoad()
// creating the refresh control object
menuButton = UIBarButtonItem.init(title: "Menu", style: .plain, target: self, action: nil)
}
It should create a UIBarButton in the navigation controller, instead there is nothing there.
You need to set navigationItem.rightBarButtonItem = menuButton
I have added a navigation bar to the top of a view controller. I am trying to control whether a button is visible based a condition, but I am having trouble adding the button. So far I have,
var addButton: UIBarButtonItem = UIBarButtonItem(title: "test", style: .done, target: self, action: #selector(addTapped))
override func viewDidLoad() {
super.viewDidLoad()
let boool = true
if boool {
self.navigationItem.rightBarButtonItem = self.addButton
}
else {
self.navigationItem.rightBarButtonItem = nil
}
}
func addTapped(sender: AnyObject) {
print("hjxdbsdhjbv")
}
I believe it is not working properly because I have added a navigation bar into the VC, instead of using a navigation controller and working with the bar there. I was wondering if there was a way to work with this navigation bar.
It’s simple. Put this line of code to the viewDidLoad:
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "test", style: .done, target: self, action: #selector(addTapped))
Updated for Swift 4 or later:
A custom function:
#objc func action(sender: UIBarButtonItem) {
// Function body goes here
}
(Custom) Right bar button item:
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "some_text", style: .done, target: self, action: #selector(self.action(sender:)))
(Custom) Left bar button item:
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "some_text", style: .done, target: self, action: #selector(self.action(sender:)))
Also you can add a system bar button items something like this: UIBarButtonItem.SystemItem Defines system-supplied images for bar button items: .add, .done, .cancel, .edit, .save, .compose, .reply, .organize and more.
(System) Right bar button item:
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonItem.SystemItem.add, target: self, action: #selector(self.action(sender:)))
(System) Left bar button item:
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonItem.SystemItem.add, target: self, action: #selector(self.action(sender:)))
let rightBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "EditImage"), style: .done, target: self, action: #selector(ViewController.call_Method))
self.navigationItem.rightBarButtonItem = rightBarButtonItem
You say you added a UINavigationBar to your view controller via storyboard, but looking at the code you provided there is no outlet connection to your navigation bar in IB.
In order to access self.navigationItem your view controller must be embedded in a UINavigationController or be part of a hierarchy which is. Unless you have a need for a custom navigation bar on an individual view controller, I suggest removing that from Interface Builder, then making sure either the view controller in question is embedded in a UINavigationController or it is being pushed onto the navigation stack from another controller which is embedded in a navigation controller and then you should see your UIBarButtonItem.
Firstly, you need to connect you navigation bar to an IBOutlet so that you can refer to it in your code. After that, this code should work:
let navigationItem = UINavigationItem(title: "Title")
navigationItem.rightBarButtonItem = self.addButton
navigationItem.hidesBackButton = true
self.navigationBar.pushItem(navigationItem, animated: false)
Swift 4.2;
Add viewController
override func viewDidLoad() {
super.viewDidLoad()
self.addNavigationBarButton(imageName: "ic_back", direction:.left)
}
Add Class your API or Utility Class
public func addNavigationBarButton(imageName:String,direction:direction){
var image = UIImage(named: imageName)
image = image?.withRenderingMode(.alwaysOriginal)
switch direction {
case .left:
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style:.plain, target: nil, action: #selector(goBack))
case .right:
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style:.plain, target: nil, action: #selector(goBack))
}
}
#objc public func goBack() {
self.navigationController?.popViewController(animated: true)
}
public enum direction {
case right
case left
}
tested in Xcode 10.2, swift 5.0;
First, I have have embedded my ViewController in UINavigationController in IB.
Then in ViewDidLoad include these lines
self.title = "orange"
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(changeLayout)).
Note - accessing title, or adding button through navigation controller did not work. For example : setting title - Self.navigationcontroller.navigationItem.title did not work ,
I want to create a navigation item "Refresh" with the default XCode refresh Icon programmatically. I know how to create one with the word "Refresh" with the following code. However, I want to have the icon insetead of the word "Refresh" Thanks for helping in advance
let refreshButton = UIBarButtonItem(title: "Refresh", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(FollowVC.refresh))
Superb question.I tried sample one for your question.I got the solution and It works fine.
what you made mistake in your coding is
First your
let refreshButton = UIBarButtonItem(title: "Refresh", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(FollowVC.refresh))
is wrong.You have to use or write
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem, target: AnyObject?, action:Selector)
Second you used UIBarButtonItemStyle.Plain.If you want refresh button you have to set UIBarButtonSystemItem.Refresh.
SWIFT
override func viewDidLoad()
{
// Create the navigation bar
let navigationBar = UINavigationBar(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: self.view.frame.size.width, height: 64))) // set frame here
//set the background color
navigationBar.backgroundColor = UIColor.white
navigationBar.delegate = self as? UINavigationBarDelegate;
// Create a navigation item with a title
let navigationItem = UINavigationItem()
navigationItem.title = "title" //If you want to set a tilte set here.Whatever you want set here.
// Create button for navigation item with refresh
let refreshButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.refresh, target: self, action: Selector(("actionRefresh:")))
// I set refreshButton for the navigation item
navigationItem.leftBarButtonItem = refreshButton
// Assign the navigation item to the navigation bar
navigationBar.items = [navigationItem]
// Make the navigation bar a subview of the current view controller
self.view.addSubview(navigationBar)
}
#pragma action method
func actionRefresh(sender: UIBarButtonItem)
{
print("The action button is refreshed")
}
Print statement is
The action button is refreshed
OBJECTIVE C
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
navbar.backgroundColor = [UIColor whiteColor];
navbar.delegate = self;
UINavigationItem * navItem = [[UINavigationItem alloc] init];
navItem.title = #"Title"; //Set Title Here Wahtever You Want Here
UIBarButtonItem *buttonRefresh = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(actionRefresh:)];
navItem.leftBarButtonItem = buttonRefresh;
navbar.items = #[navItem];
[self.view addSubview:navbar];
}
The NSLog statement is
The button action refresh is performed
See the refresh button in screenshot
Good Solutions
Add Default Icons to Navigation Bar
Navigation Bar Item Programmatically
Adding Navigation Bar item Programmatically
Instead of using .Plain, you should be using .Refresh.
let refreshButton = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: #selector(FollowVC.refresh))
Also you should be using the init(barButtonSystemItem:target:action:) instead of the init(title:style:target:action:).
I have a question to add a right button in navigation bar..
I have two views: View A and View B
I add a navigation bar to view A, after I used self.navigationController!.pushViewController to show view B.
That show a back button in the left of navigation bar of view B automatic, it is good. but now I want to add a button in the right of navigation bar of view B..
I have tried some answers, but it doesn't work...
I have tried answers likes :
1) https://www.hackingwithswift.com/example-code/uikit/how-to-add-a-bar-button-to-a-navigation-bar
2)http://blog.apoorvmote.com/add-multiple-bar-button-item-navigation-bar/?lang=fr
Could you help me, thank you !
The Swift version of Vahan Babayan's answer, as you seem to use this language, is:
let rightButtonItem = UIBarButtonItem.init(
title: "Title",
style: .Done,
target: self,
action: "rightButtonAction:"
)
self.navigationItem.rightBarButtonItem = rightButtonItem
The following method will be called on self:
func rightButtonAction(sender: UIBarButtonItem)
Note that all this can be set graphically using a Storyboard, by dragging a Bar Button Item to your Navigation Item and right-clicking to set a target-action.
A small update since Swift 3 and 4 are out: the compiler can now check selector names, preventing typos when setting up target-action programatically. So one should really use:
let rightButtonItem = UIBarButtonItem.init(
title: "Title",
style: .Done,
target: self,
action: #selector(rightButtonAction(sender:))
)
You can add the following code to your B controller's viewDidLoad method.
UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Title"
style:UIBarButtonItemStyleDone
target:self
action:#selector(rightButtonAction:)];
self.navigationItem.rightBarButtonItem = rightButtonItem;
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc]initWithTitle:#"Right Button" style:UIBarButtonItemStyleDone target:self action:#selector(rightBtnClick)];
self.navigationItem.rightBarButtonItem = rightBtn;
}
-(void)rightBtnClick{
// code for right Button
}
Add below code in viewDidLoad Method
UIBarButtonItem *flipButton = [[UIBarButtonItem alloc]
initWithTitle:#"Flip"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(flipView:)];
self.navigationItem.rightBarButtonItem = flipButton;
This adds a button to the right hand side with the title Flip, which calls the method:
-(IBAction)flipView
Swift code to add a navigation bar button item:
Method 1 (When you wanna use bar button system item)
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))
Method 2 (When you wanna give your own title to button)
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(addTapped))
From iOS 5 onwards, it allows you to add more than 1 button on either side of a navigation bar. Something like this:
let add = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))
let display = UIBarButtonItem(title: "Display", style: .plain, target: self, action: #selector(playTapped))
navigationItem.rightBarButtonItems = [add, display]
Try this code for Swift UI :
.navigationBarItems(
leading:
HStack {
Button("About") {
print("About tapped!")
}
Button("Call") {
print("Call tapped!")
}
},
trailing:
HStack {
Button("Settings") {
print("Settings tapped!")
}
Button("Contacts") {
print("Contacts tapped!")
}
}
)
In my application I want to use 'Back' text as back button title for every viewcontroller.
I have read so many posts on stackoverflow but got nothing.
I don't want to set leftbarbuttonitem.
Can anyone help me on this simple task.
Thanks,
Do this in the parent view controller not in the child
Swift
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil)
Objetive-C
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationController.navigationBar.topItem.title = #"";
If you are using storyboard you can select the navigation item in the parent view controller and set the button text you want in 'Back Button' field. Remember to set this in the parent view controller, not in the child that is pushed.
Try this hope it will be work
UIBarButtonItem *btn =
[[UIBarButtonItem alloc] initWithTitle:#"New Title"
style:UIBarButtonItemStyleBordered
target:nil
action:nil];
[[self navigationItem] setBackBarButtonItem:btn];
I needed to use self.navigationController.navigationBar.backItem.title = #"";, the difference being that I'm using backItem instead of topItem.
Back Button With Back Arrow
Objective-C
self.navigationController.navigationBar.topItem.backBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:#"Title" style:UIBarButtonItemStylePlain
target:nil action:nil];
Swift
self.navigationController?.navigationItem.backBarButtonItem =
UIBarButtonItem(title:"Title", style:.plain, target:nil, action:nil)
Normal Button Without Back Arrow
Objective-C
self.navigationItem.leftBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:#"Title"
style:UIBarButtonItemStylePlain target:nil action:nil];
Swift
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title:"Title",
style:.plain, target:nil, action:nil)
Bold Button Without Back Arrow
Objective-C
self.navigationItem.leftBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:#"Title"
style:UIBarButtonItemStyleDone target:nil action:nil];
Swift
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title:"Title",
style:.done, target:nil, action:nil)
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
Changes the currently visible Back Button
extension UIViewController {
func setCurrentBackButton(title: String) {
guard let vcCount = self.navigationController?.viewControllers.count else {
return
}
let priorVCPosition = vcCount - 2
guard priorVCPosition >= 0 else {
return
}
self.navigationController?.viewControllers[priorVCPosition].navigationItem.backBarButtonItem = UIBarButtonItem(title: title, style: .plain, target: self, action: nil)
}
swift 2.0:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.topItem?.title = ""
}
Note: It works only if storyboard have a chain of navigation stack.
Other options/changing title:
self.navigationController?.navigationBar.backItem?.title = ""
navigationItem.backBarButtonItem?.title = ""
navigationItem.leftBarButtonItem?.title = ""
Removing navigationItem:
navigationItem.setLeftBarButtonItem(nil, animated: true)
To remove back button title for all view controller add new swift file and copy this extinction to it
import UIKit
extension UIViewController {
static func swizzle(){
let orginalSelector = #selector(viewDidLoad)
let swizzledSelector = #selector(swizzledViewDidLoad)
let orginalMethod = class_getInstanceMethod(UIViewController.self, orginalSelector)
let swizzledMethod = class_getInstanceMethod(UIViewController.self, #selector(swizzledViewDidLoad))
let didAddMethod = class_addMethod(UIViewController.self, orginalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
if didAddMethod {
class_replaceMethod(UIViewController.self, swizzledSelector, method_getImplementation(orginalMethod!), method_getTypeEncoding(orginalMethod!))
}else{
method_exchangeImplementations(orginalMethod!, swizzledMethod!)
}
}
#objc func swizzledViewDidLoad(){
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
swizzledViewDidLoad()
}
}
After that in AppDelegate inside didFinishLaunchingWithOptions, call the swizzle function.
UIViewController.swizzle()
This function is using the objective c runtime to exchange the viewDidLoad method with another one that removes the back button title and then inside it recall the original viewDidLoad.
in AppDelegate in the DidFinishLaunchingWithOptions add this code:
[[UIBarButtonItem appearance]
setBackButtonTitlePositionAdjustment:UIOffsetMake(-1000.0, 0.0)
forBarMetrics:UIBarMetricsDefault];