UIBarButtonItem disable animation - ios

I have an UIBarButtonItem, which is a non-clickable logo. How do I disable the touch animation for this logo?
I have tried getting at the view:
let view = self.appTitle.performSelector(Selector("view")).takeRetainedValue() as? UIView
view?.userInteractionEnabled = false
but then the app crashes.
The UIBarButtonItem is inside a UiToolbar, created in a storyboard.

This works:
self.appTitle.customView = UIImageView(image: UIImage(named: "footer"))

If you want UIBarButtonItem be don't clicked use
barBtnItem.enabled = false

let transitionOptions: UIViewAnimationOptions = [.TransitionCrossDissolve, .ShowHideTransitionViews]
UIView.transitionWithView(#yourUIBarButtonItem outlet, duration: 1.0, options: transitionOptions, animations: {
self.#yourUIBarButtonItem outlet.enabled = false
}, completion: nil)

If your UIBarButtonItem is in NavigationItem then first assign it to leftBarButtonItem or rightBarButtonItem and then set enabled property of UIBarButtonItem to NO in objective-c and false in swift
Objective-C:
UIImage *menuImage = [UIImage imageNamed:#"menu"];
UIButton *menu = [UIButton buttonWithType:UIButtonTypeCustom];
menu.frame = CGRectMake( 10, 0, menuImage.size.width, menuImage.size.height);
[menu addTarget:self action:#selector(handleBack:) forControlEvents:UIControlEventTouchUpInside];
[menu setImage:menuImage forState:UIControlStateNormal];
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:menu];
self.navigationItem.leftBarButtonItem = backButton;
self.navigationItem.leftBarButtonItem.enabled = NO;
Swift:
var menuImage: UIImage = UIImage(named: "menu")!
var menu: UIButton = UIButton(type: .Custom)
menu.frame = CGRectMake(10, 0, menuImage.size.width, menuImage.size.height)
menu.addTarget(self, action: #selector(self.handleBack), forControlEvents: .TouchUpInside)
menu.setImage(menuImage, forState: .Normal)
var backButton: UIBarButtonItem = UIBarButtonItem(customView: menu)
self.navigationItem.leftBarButtonItem = backButton
self.navigationItem.leftBarButtonItem.enabled = false

Related

How to change UINavigationBar rightButton image? [duplicate]

This question already has answers here:
Changing the UINavigationBar background image
(7 answers)
Closed 6 years ago.
I want to change UINavigationBar rightButton image in viewWillAppear and for this I'm trying this:
self.navigationController?.navigationItem.rightBarButtonItem?.image = UIImage(named: "bookmark")
but it does not change the image of my rightButton. How can I fix it and change my image?
try this
var changeImage:UIImage = UIImage(named: "bookmark")!
changeImage = changeImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
var rightButton = UIBarButtonItem(image: changeImage, style: UIBarButtonItemStyle.Bordered, target: self, action: "xxxx")
self.navigationItem.rightBarButtonItem = rightButton
Choice-2
for book mark use default function of UIBarButtonSystemItemBookmarks
var rightButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Bookmarks, target: self, action: "xxxx")
self.navigationItem.rightBarButtonItem = rightButton
some default UIBarbuttonItems are
typedef NS_ENUM(NSInteger, UIBarButtonSystemItem) {
UIBarButtonSystemItemDone,
UIBarButtonSystemItemCancel,
UIBarButtonSystemItemEdit,
UIBarButtonSystemItemSave,
UIBarButtonSystemItemAdd,
UIBarButtonSystemItemFlexibleSpace,
UIBarButtonSystemItemFixedSpace,
UIBarButtonSystemItemCompose,
UIBarButtonSystemItemReply,
UIBarButtonSystemItemAction,
UIBarButtonSystemItemOrganize,
UIBarButtonSystemItemBookmarks,
UIBarButtonSystemItemSearch,
UIBarButtonSystemItemRefresh,
UIBarButtonSystemItemStop,
UIBarButtonSystemItemCamera,
UIBarButtonSystemItemTrash,
UIBarButtonSystemItemPlay,
UIBarButtonSystemItemPause,
UIBarButtonSystemItemRewind,
UIBarButtonSystemItemFastForward,
UIBarButtonSystemItemUndo NS_ENUM_AVAILABLE_IOS(3_0),
UIBarButtonSystemItemRedo NS_ENUM_AVAILABLE_IOS(3_0),
UIBarButtonSystemItemPageCurl NS_ENUM_AVAILABLE_IOS(4_0),
};
self.navigationController?.navigationItem.rightBarButtonItem?.image= UIBarButtonItem(image: //Image Name, style: UIBarButtonItemStyle.Plain, target: self, action: //ACTION NAME)
Try this, I am new to swift that's why i've done this code in Objective C.
UIButton *btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
[btnRight setFrame : CGRectMake(0, 0, 60, 35)];
[btnRight setImage:[UIImage imageNamed:#"prefferedImage"] forState:UIControlStateNormal];
[btnRight addTarget:self action:#selector(defindeActionMethod:) forControlEvents:UIControlEventTouchUpInside];
[btnRight setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
btnRight.imageView.contentMode = UIViewContentModeScaleAspectFit;
btnRight.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
btnRight.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:btnRight];
[rightBarButton setTintColor:[UIColor whiteColor]];
self.navigationItem.rightBarButtonItem = rightBarButton;

How to change space between UIBarButtonItems in UINavigationBar?

This is how it looks now:
This is how it is represented in Debug view Hierarchy:
And here is how I set it up in code:
func setupUserAndCartButtons() {
var rightBarButtonItems = [UIBarButtonItem]()
let cartBarButtonItem = UIBarButtonItem(image: DBCart.sharedCart().icon, style: .Plain, target: self, action: Selector("cartButtonTapped:"))
rightBarButtonItems.append(cartBarButtonItem)
let userIcon = UIImage(named: "icon-user")
let userBarButtonItem = UIBarButtonItem(image: userIcon, style: .Plain, target: self, action: Selector("userButtonTapped:"))
rightBarButtonItems.append(userBarButtonItem)
navigationItem.rightBarButtonItems = rightBarButtonItems
}
Hot to move them closer to each other without using custom view?
use imageInsets property of UIBarButtonItem
In Objective-C
[addContact setImageInsets:UIEdgeInsetsMake(0, -10,0, 0)];
Swift 4.1
buttonName.imageInsets = UIEdgeInsetsMake(0, 30, 0, 0)
This will move button to right side to other button.
Hope this will help someone
Add buttons using custom View:
//MARK:Customize Navigation Bar
func addButtonsToNavigationBar(){
let cartButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
cartButton.frame = CGRectMake(0,0,20,20)
cartButton.addTarget(self, action: "cartButtonTapped:", forControlEvents: .TouchUpInside)
cartButton.setImage(UIImage(named: DBCart.sharedCart().icon), forState: .Normal)
let cartBarButtonItem = UIBarButtonItem(customView: cartButton)
let userButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
userButton.frame = CGRectMake(0,0,20,20)
userButton.addTarget(self, action: "userButtonTapped:", forControlEvents: .TouchUpInside)
userButton.setImage(UIImage(named: "icon-user"), forState: .Normal)
let userBarButtonItem = UIBarButtonItem(customView: userButton)
self.navigationItem.rightBarButtonItems=[cartBarButtonItem,userBarButtonItem]
}
UIBarButtonSystemItemFixedSpace is used to adjust spacings of navigation bar items.
Example code:
- (void)setRightBarButtonItems {
UIBarButtonItem *addTaskButton =
[[UIBarButtonItem alloc] bk_initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
handler:handler];
UIBarButtonItem *negativeSeperator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
if ([UIDevice isIOS7Plus]) {
negativeSeperator.width = -12;
} else {
negativeSeperator.width = -8;
}
UIBarButtonItem *separator = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
separator.width = 50;
[self.navigationItem setRightBarButtonItems:#[addTaskButton, separator, [self filterButton]]];
}

How to set Navigation back button icon in all view controller like globally?

I can perform operation to set navigation back button icon on all the views commonly. For example if I put code in App Delegate method then it's used for all the controllers.
Here is The final Answer which i have used in my current App hope it will useful..
in view DidLoad method..
UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
leftButton.frame = CGRectMake(0, 0, 40, 40);
[leftButton setImage:[UIImage imageNamed:#"Back"] forState:UIControlStateNormal];
[leftButton addTarget:self action:#selector(left_menu_click:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
self.navigationItem.leftBarButtonItem = leftBarButtonItem;
add this method for navigate popViewController..
-(IBAction)left_menu_click:(id)sender{
[self.navigationController popViewControllerAnimated:YES];
}
You may try below appearance with correct image for back button throughout app.
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:[UIImage imageNamed:#"back_button_bg"]
forState:UIControlStateNormal
barMetrics:UIBarMetricsDefault];
You may try custom button like this:
+ (UIBarButtonItem *)backButtonForTarget:(id)target
{
UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn addTarget:target action:#selector(back) forControlEvents:UIControlEventTouchUpInside];
[btn setFrame:CGRectMake(0, 0, 70, 44)];
[btn setImageEdgeInsets:UIEdgeInsetsMake(11, -10, 8, 35)];
[btn setImage:[UIImage imageNamed:#"topbar_back.png"] forState:UIControlStateNormal];
UIBarButtonItem *barbtnItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
return barbtnItem;
}
add this button as leftBarButtonItem
self.navigationItem.leftBarButtonItem = [UtilityClass backButtonForTarget:self];
Add following code in didFinishLaunchingWithOptions method in AppDelegate class :
// Following line is for tint color that is optional, You can add if you wants to change color of back button
[[UIBarButtonItem appearance] setTintColor:[UIColor redColor]];
If you want change background images then
// Change the appearance of back button
UIImage *backButtonImage = [[UIImage imageNamed:#"button_back"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 13, 0, 6)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
Just found a solution using appearance()
Swift
let backImage = UIImage(named: "back")
UINavigationBar.appearance().backIndicatorImage = backImage
UINavigationBar.appearance().backIndicatorTransitionMaskImage = backImage
UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor:
UIColor.white], for: .normal)
UIBarButtonItem.appearance().tintColor = UIColor.green
You should modify UINavigationBar like:
let appearance = UINavigationBar.appearance()
appearance.backIndicatorImage = image
appearance.backIndicatorTransitionMaskImage = image
If you want to remove default title, you add:
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
to view controller that pushes to the navigation controller.
You can find more on Apple docs
You can try this
let backImage = UIImage(named: "icon")
let backImageUIEdgeInsets = UIEdgeInsets(top: -4, left: -8, bottom: -2, right: 8)
let backImageWithAlignmentRectInsets = backImage?.withAlignmentRectInsets(backImageUIEdgeInsets)
appearance.setBackButtonBackgroundVerticalPositionAdjustment(-1.0, for: .default)
appearance.setBackButtonBackgroundImage(backImageWithAlignmentRectInsets,
for: .normal,
barMetrics: .default)
appearance.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.clear],
for: .normal)
appearance.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.clear],
for: .highlighted)

How can I change the background color of a UIBarButtonItem on iOS 7+?

I'd like to indicate that a particular UIBarButtonItem is toggled on or off by changing its background color. Mobile Safari uses this feature to indicate whether private browsing is on or off:
How can I do this, since there's no backgroundColor property on UIBarButtonItem?
Create a UIButton and use it as the custom view for the UIBarButtonItem. Then, set the backgroundColor on the button's layer:
UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:#"Test"];
button.layer.backgroundColor = [UIColor redColor].CGColor;
button.layer.cornerRadius = 4.0;
UIBarButtonItem* buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.toolbarItems = #[buttonItem];
You could instead just use two images. One for selected and one for unselected
- (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics
The above function should help you do this
Swift 5 Answer
let rightBarCancelButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
let cancelImage = UIImage(systemName: "multiply")
rightBarCancelButton.setImage(cancelImage, for: .normal)
rightBarCancelButton.layer.cornerRadius = 15
rightBarCancelButton.backgroundColor = UIColor.lightGray
let rightBarButton = UIBarButtonItem(customView: rightBarCancelButton)
navigationItem.rightBarButtonItem = rightBarButton
Works like a charm!

Add border in UIBarButtonItem

In my app, I have designed a view in the interface builder.
This view has a toolbar, with some UIBarButtonItem in.
My buttons can be custom images, or default button like share, add,...
Now with iOS7, buttons don't have anymore borders. So I'd like to add some.
Here is what i want to do : add borders like the white lines on my screenshot.
What I've tried is to add a UIButton to the toolbar. In my example, I've set my back button size (12x44). I add this button as a IBOutlet property of my view controller, and try to draw a border to it :
CALayer *cancelBorder = [CALayer layer];
[cancelBorder setFrame:CGRectMake(12, 0, 1, 44)];
[backBorder setBackgroundColor:[[UIColor whiteColor] CGColor]];
[backButton.layer addSublayer:cancelBorder];
But it doesn't work. Anyone has a solution?
Adding UIBarButtonItem to toolbar programmatically may solve your problem.
First, create custom button with images, borders, etc. As HereTrix said, you can add border to this button.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(10, 0, 30, 30);
button.layer.borderColor = [UIColor blueColor].CGColor;
button.layer.borderWidth = 1.0f;
/* any other button customization */
Then, initialize UIBarButtonItem with that custom button and add this item to your toolbar.
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.toolBar.items = #[backButton];
Swift 3 : Below is my full implementation for button customization and event handling.
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton.init(type: .custom)
button.setTitle("Tester", for: .normal)
button.setTitleColor(.darkGray, for: .normal)
button.layer.borderWidth = 1
button.layer.cornerRadius = 5
button.layer.borderColor = UIColor.darkGray.cgColor
button.addTarget(self, action: #selector(self.handleButton), for: .touchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let button = self.navigationItem.rightBarButtonItem?.customView {
button.frame = CGRect(x:0, y:0, width:80, height:34)
}
}
func handleButton( sender : UIButton ) {
// It would be nice is isEnabled worked...
sender.alpha = sender.alpha == 1.0 ? 0.5 : 1.0
}
Hope this helps

Resources