I have added one custom bar button in my app.I want to set it's title but i am not able to set its title.I am using below code in swift 3.Please advice the best solution.
let customButton=UIButton(frame: CGRect(x: 0, y: 0, width: 60, height:30))
customButton.backgroundColor=Constant.Color.customBlue
customButton.titleLabel?.text = "Add"
customButton.titleLabel?.textColor=UIColor.white
let barButton = UIBarButtonItem(customView:customButton)
barButton.title="Add"
barButton.tintColor=UIColor.white
self.navigationItem.rightBarButtonItem=barButton
You need to set title as below :
customButton?.setTitle("Add", for:.normal)
You have to use this:
[customButton setTitle:#"Add" forState:UIControlStateNormal];
Try This code:
Note: This is a better approach to apply barButton to your navigationBar with action.
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(addTapped))
func addTapped() {
//Do your stuff here. After Add button pressed
print("Add Button Pressed")
}
If you still want to use your code.Add the following code to set title to your button as KKRocks answer.
customButton?.setTitle("Add", for:.normal)
Related
I'd like to be able to change only the text color of the back button in the navigation bar.
As a work around, I can sort of do what I'm trying to do by creating a custom view and assigning it to navigationItem.leftBarButtonItem, but it doesn't look very good and I also lose the swipe to pop ability.
Code for the above:
let button = UIButton(type: .system)
let originalImage = #imageLiteral(resourceName: "BackButton")
let scaledImage: UIImage = UIImage(cgImage: originalImage.cgImage!, scale: 30, orientation: originalImage.imageOrientation)
button.setImage(scaledImage, for: .normal)
button.setTitle("YourTitle", for: .normal)
button.sizeToFit()
button.setTitleColor(.brown, for: .normal)
button.tintColor = .blue
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
I also see things suggested like setting attributes of the back button via
navigationController?.navigationBar.topItem.backBarButtonItem?.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .normal)
but that doesn't seem to have any effect on the look of the text, despite
print("Attributes: ", navigationController?.navigationBar.topItem?.backBarButtonItem?.titleTextAttributes(for: .normal) ?? "No attributes")
resulting in Attributes: ["NSColor": UIExtendedSRGBColorSpace 1 0 0 1].
I could set tintColor but that would change the color of the back icon in addition to the title.
So what's the best way to do what I want? Is there a way?
Am not sure whether I understood you correctly. But try the below code. This will apply to all the bar button items of your app. Place this code where it is called only once though out app lifecycle. Like application: didFinishLaunchingWithOptions:
let attribs = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18)]
UIBarButtonItem.appearance().setTitleTextAttributes(attribs, for: .normal)
I figured it out. You can style the back button by setting self.navigationItem.backBarButtonItem in the previous view controller.
For example, in my case I had TableViewController and when you clicked on a cell, the app would transition to ViewController. In TableViewController I had
public func changeColor() {
let barButton = UIBarButtonItem(title: "Anything", style: .plain, target: nil, action: nil)
barButton.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.brown], for: .normal)
self.navigationItem.backBarButtonItem = barButton
}
and then in ViewController I had
#IBAction func buttonPressed(_ sender: Any) {
let vc = self.navigationController?.viewControllers[0] as! TableViewController
vc.changeColor()
self.title = "hello very long title asdfasdfasfdasdfasdfasdfasdfasdf"
}
As a result, pressing a button in ViewController would change the color of the title of its back button to brown.
Hi I saw too many tutorial from stack overflow for how to change backBarButton I change it but when I check I see my image(custom arrow) beside (default arrow blue one ) I see both beside of each other
I mean the back text changed but the arrow doesn't I see my custom arrow beside default iOS arrow I don't know how should I change it to see my custom arrow only ???
for more detail please check this picture to see this problem
HERE
First You need to hide the default back Button , then supply your Custom one. Following code will help you.
self.navigationItem.hidesBackButton = true
let back: UIButton = UIButton(type: UIButtonType.custom)
back.setImage(UIImage(named: "backarrow"), for: UIControlState.normal)
back.frame = CGRect(x: 0, y: 0, width: 22, height: 22)
back.addTarget(self, action: #selector(self.backPressed), for: UIControlEvents.touchUpInside)
let left: UIBarButtonItem = UIBarButtonItem(customView: back)
self.navigationItem.setLeftBarButton(left, animated: true)
self.navigationController?.navigationBar.topItem?.title = ""
func backPressed() {
//Do your menupulation
}
If I understand you correctly you just need to place your button into Navigation Bar and then set your image name into "image" field.
http://take.ms/Rfrtf - here is for example ;)
Solution 1
You can set default back button color's tint color to red .
UINavigationBar.appearance().tintColor = UIColor.red // add this line appdelegate
Solution 2
self.navigationItem.leftItemsSupplementBackButton = YES;
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)
or
self.navigationItem.leftBarButtonItems = #[customBackButtonItem];
I have the following code:
func navbarbutton() {
UIView.animateWithDuration(0.2, animations: { () -> Void in
let current = self.navigationController?.navigationBar.frame
self.navigationController?.navigationBar.frame = CGRectMake(self.frame!.origin.x, self.frame!.origin.y, self.frame!.size.width, current!.size.height + 50)
self.navigationController?.navigationBar.layoutIfNeeded()
})
}
I'm able to increase the height of the navigation bar by 50 dp. That's not the issue for me. The issue I'm having is that the UIBarButtonItems are all aligned to the bottom. How can I get them aligned to the top so that I can add more to the bottom myself? I'm getting something as per the image:
Is it possible to get it aligned to the top?
Unfortunately you can't do that.
The view hierarchy within the UINavigationBar is private so you can't manipulate it without iterating over the subviews and going all hacky with it. This probably isn't a good idea.
Out of curiosity I looked at the Messages app in iOS 10 using the view debugger because they obviously do this. They actually achieve the layout by adding their own UIButton to replace the back and rightBarButtonItem. This is something you would be able to do however they also set the alpha of one of the internal (and private) content views to zero so that the original content is no longer visible.
This is something that you won't be able to do so easily unfortunately. You could try to hack things about until it works but remember you also need to handle pushes/pops, in call status bars, interactive transitions and rotation events.
If however you wasn't going for the iMessage style and just wanted to add some content underneath your navigation bar, why not look at pinning a UIVisualEffectView to the topLayoutGuide in your UIViewController? You can get a fairly nice look pretty easily and it saves hacking stuff about a lot. Here's an example:
Try this code:
Note: Code tested in Swift 3.
Answer 1: Updated Answer
class ViewController: UIViewController {
var customBar: UINavigationBar = UINavigationBar()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Title
title = "Some Title"
// Add bar button item
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(addTapped))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(addTapped))
self.customBar.frame = CGRect(x:0, y:0, width:view.frame.width, height:(navigationController?.navigationBar.frame.height)! + 50)
self.customBar.backgroundColor = UIColor.green
self.view.addSubview(customBar)
}
func addTapped() {
print("Button Pressed")
}
Output:
Answer 2:
override var isViewLoaded: Bool {
// Add bar button item
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(addTapped))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(addTapped))
//Vertical and Horizonal barButtonItem position offset
navigationItem.leftBarButtonItem?.setTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: 20), for: UIBarMetrics.default)
navigationItem.rightBarButtonItem?.setTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: 20), for: UIBarMetrics.default)
return true
}
func addTapped() {
print("Button Pressed")
}
Note: Above code only works in isViewLoaded: Bool method.But, No luck.When, I tried this code in other viewLoad method.
Output 1: barButtonItem moved 20 pixel up vertically.
Output 2: barButtonItem moved 20 pixel down vertically.
Hope, Above code fix your problem.
I'm currently working on a snapchat-like menu where clicking the left and right UIBarButtonItem makes the screen go in their respective directions.
TL;DR - I'm wondering if there's a (clean) built-in way of passing through a tag as an Optional type to avoid crashes.
override func viewDidLoad() {
super.viewDidLoad()
// Other setup code here
let leftButton = UIBarButtonItem(title: leftButtonString, style: UIBarButtonItemStyle.Plain, target: self, action: "navButtonClicked:")
let rightButton = UIBarButtonItem(title: rightButtonString, style: UIBarButtonItemStyle.Plain, target: self, action: "navButtonClicked:")
// These tags are not a good solution because they aren't optionals!
leftButton.tag = 0
rightButton.tag = 1 // this isn't necessary, but I don't want it to crash...
// More setup here
}
func navButtonClicked(sender: UIBarButtonItem) {
// Goes right by default
let currentX = self.parentScrollView!.contentOffset.x
var screenDelta = self.parentScrollView!.frame.width
if sender.tag == 0 {
screenDelta *= -1
}
UIView.animateWithDuration(0.5, animations: {() in
self.parentScrollView!.contentOffset = CGPoint(x: currentX + screenDelta, y: 0)
})
}
My current solution works, I'm just working towards writing cleaner code.
Thanks!
Option 1:
Create two properties in your view controller that correspond to each UIBarButtonItem. This way you'll be able to tell which one was tapped.
Option 2:
Sublass UIBarButtonItem and add a property that you want.
I have made a custom bar button item at my navigation controller and it was working fine but it doesn't anymore.
This is the lines that I use to make the custom bar button :
func addSlideMenuButton(){
let btnShowMenu = UIButton(type: UIButtonType.Custom)
//btnShowMenu.setImage(self.defaultMenuImage(), forState: UIControlState.Normal)
btnShowMenu.setImage(UIImage(named: "barBtnMenu"), forState: UIControlState.Normal)
btnShowMenu.frame = CGRectMake(0, 0, 30, 30)
btnShowMenu.addTarget(self, action: "onSlideMenuButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
let customBarItem = UIBarButtonItem(customView: btnShowMenu)
// self.navigationItem.rightBarButtonItem = customBarItem;
self.navigationItem.leftBarButtonItem = customBarItem;
}
the image exists and there is no error or crash .
Even If I add the bar button item from soryboard , When I run the application it would hidden my bar button item.
What could be wrong ?
func addSlideMenuButton() {
let customBarItem = UIBarButtonItem(image: UIImage(named: "barBtnMenu"), style: .Plain, target: self, action: "onSlideMenuButtonPressed")
self.navigationItem.leftBarButtonItem = customBarItem;
}
A couple of options come to mind
Are you sure you're not setting navigationItem.hidesBackButton = true anywhere in that UIViewController?
Are you sure you're not adding another UINavigationBar on top of the one provided by the system?