What I Want: A border indicating if a UIButton is selected or not.
Background: I've got some UIButtons using transparent images, not text. These are toggle buttons (i.e. can be on or off).
Problem: The UIButton class gives users no indication of whether a button is selected or not unless you change something else about the button. Since the image doesn't change with the state, I'd need two of every image, one normal, one selected and set one for each state of the button. This is annoying. I thought instead I'd change the background image, but this removes the pretty border on the button, I just get a rectangle of my background image, yuck.
Possible solutions I don't like:
1) Create a background that matches the UIButton border and use that for selected. I don't like this because they wont match perfectly and I'm picky.
2) Create two images for each button, essentially identical but with a different background. This seems like unnecessary work, and since this problem is coming up repeatedly, I want a solution for the future as well.
I hope somebody's figured out a decent solution to this by now. Thanks in advance.
Since UIButton has two image layers, an image and a background image, I think you could accomplish what you want by using just two background images for all your buttons. One image shows a border and the other does not. Swap the backgrounds out when the control state changed.
//
// TabBarSingleton.h
#import <Foundation/Foundation.h>
#interface TabBarSingleton : UITabBarController <UITabBarControllerDelegate>{
NSRecursiveLock *barLock;
UIButton *Button;
UIButton *favoriteButton;
}
#property(nonatomic, retain) UIButton *Button;
#property(nonatomic, retain) UIButton *favoriteButton;
- (void) ButtonPressed;
- (void) favoriteButtonPressed;
#end
///////////////////////////////////
If you want the the borders only, then you have only one choice of using two images for the two states otherwise if your purpose is to differentiate between two states then you can do it by changing alpha a little bit of the selected button this will give the effect like toggle buttons, you can also disable the selected button and enable it again when the other button is pressed.
Hope this will give you a fair idea.
//
// TabBarSingleton.m
// Created by ArunDhwaj on 9/7/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import "TabBarSingleton.h"
#implementation TabBarSingleton
#synthesize Button, favoriteButton;
- (id) init
{
if (self = [super initWithNibName: nil bundle: nil])
{
barLock = [[NSRecursiveLock alloc] init];
}
self.delegate = self;
return self;
}
+ (TabBarSingleton *) defaultBar
{
}
- (void)viewDidLoad
{
NSLog(#"TabBarSingleton: viewDidLoad");
//Hiding TabBar
self.tabBar.hidden = YES;
//Creating a UIView, its frame is same as tabBar frme
CGRect tabbarFrame = self.tabBar.frame;
UIView* customTabbarView = [[UIView alloc] initWithFrame:tabbarFrame];
UIImageView *newsFeedImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"newsfeeds_normal.png"]];
newsFeedImg.frame = CGRectOffset(newsFeedImg.frame, 0, 1);
Button = [UIButton buttonWithType:UIButtonTypeCustom];
[Button setFrame:newsFeedImg.frame];
[Button setBackgroundImage:newsFeedImg.image forState:UIControlStateNormal];
[Button setBackgroundImage:[UIImage imageNamed:#"newsfeeds_active.png"] forState:UIControlStateHighlighted];
[Button addTarget:self action:#selector(newsFeedsButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[customTabbarView addSubview:Button];
//[newsFeedImg release];
CGRect newsFeedFrame = newsFeedImg.frame;
UIImageView *favoriteImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"favorites_normal.png"]];
favoriteImg.frame = CGRectMake(newsFeedFrame.size.width, newsFeedFrame.origin.y, newsFeedFrame.size.width, newsFeedFrame.size.height);
favoriteButton = [UIButton buttonWithType:UIButtonTypeCustom];
[favoriteButton setFrame:favoriteImg.frame];
[favoriteButton setBackgroundImage:favoriteImg.image forState:UIControlStateNormal];
[favoriteButton setBackgroundImage:[UIImage imageNamed:#"favorites_active.png"] forState:UIControlStateHighlighted];
[favoriteButton addTarget:self action:#selector(favoriteButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[customTabbarView addSubview: favoriteButton];
//[favoriteImg release];
[self.view addSubview:customTabbarView ];
[self newsFeedsButtonPressed];
}
- (void) newsFeedsButtonPressed
{
NSLog(#"TabBarSingleton: newsFeedsButtonPressed");
self.selectedIndex = 0;
//Keeping Highlighted newsFeed tab
UIImageView *newsFeedImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"newsfeeds_active.png"]];
[Button setImage: newsFeedImg.image forState:UIControlStateNormal];
//Keeping normal others tab icons
UIImageView *favoriteImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"favorites_normal.png"]];
[favoriteButton setImage: favoriteImg.image forState:UIControlStateNormal];
}
- (void) favoriteButtonPressed
{
NSLog(#"TabBarSingleton: favoriteButtonPressed");
self.selectedIndex = 1;
//Keeping Highlighted newsFeed tab
UIImageView *newsFeedImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"newsfeeds_normal.png"]];
[Button setImage: newsFeedImg.image forState:UIControlStateNormal];
//Keeping normal others tab icons
UIImageView *favoriteImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"favorites_active.png"]];
[favoriteButton setImage: favoriteImg.image forState:UIControlStateNormal];
#pragma mark UITabBarControllerDelegate
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
NSLog(#"TabBarSingleton: shouldSelectViewController");
return YES;
}
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
NSLog(#"TabBarSingleton: didSelectViewController");
}
- (void) dealloc
{
//[barLock release];
[super dealloc];
}
#end
Related
UIAlertView is working fine in ios 6 with below code .But when it comes to ios 7 the subviews ( "yes" and "no" buttons in my code ) is not showing when alertview is called only text message is showing .Can anyone tell me how to resolve this problem ?
viewController.m file
[Utilities prCustomAlert:#"Textmessage" inTitle:#"Alert view title" delegate:self inTag:300];
CustomAlertView *alertView = [Utilities sharedUtility].customAlertView;
alertView.numberOfBtns = 2;
UIButton *btn= (UIButton *)[alertView viewWithTag:10];
[btn setTitle:#"no" forState:UIControlStateNormal];
[btn addTarget:self action:#selector(dontlogout) forControlEvents:UIControlEventTouchDown];
btn = (UIButton *)[alertView viewWithTag:11];
[btn setTitle:#"yes" forState:UIControlStateNormal];
[btn addTarget:self action:#selector(logout) forControlEvents:UIControlEventTouchDown];
[Utilities displayCustomAlertForDelegate:self];
UIAlertView.m file
CGRect viewFrame = self.frame;
CGRect buttonFrame = button.frame;
if(self.numberOfBtns==2){
CGRect labelFrame = [self viewWithTag:15].frame;
button.frame = CGRectMake(10, 0, 40, 30);
button.hidden = NO;
//yes...
btn = (UIButton *)[self viewWithTag:11];
btn.frame = CGRectMake(60, 0, 40, 30);
btn.hidden = NO;
//no..
btn = (UIButton *)[self viewWithTag:10];
btn.hidden = YES;
}
We can add subviews to UIAlerView by adding subview to the presentedViewController's view when UIAlertView is presented. I have accessed UIAlertView like following way :
NSArray *subviews = [UIApplication sharedApplication].keyWindow.rootViewController.presentedViewController.view.subviews;
I have created a subclass of UIAlerView :
Header File :
#interface MLKLoadingAlertView : UIAlertView
- (id)initWithTitle:(NSString *)title;
#end
Implementation File :
#import "MLKLoadingAlertView.h"
#define ACTIVITY_INDICATOR_CENTER CGPointMake(130, 90)
#implementation MLKLoadingAlertView
- (id)initWithTitle:(NSString *)title
{
if ( self = [super init] )
{
self.title = title;
self.message = #"\n\n";
[self setDelegate:self];
}
return self;
}
// You can Customise this based on your requirement by adding subviews.
- (void)didPresentAlertView:(UIAlertView *)alertView
{
NSArray *subviews = [UIApplication sharedApplication].keyWindow.rootViewController.presentedViewController.view.subviews;
if( subviews.count > 1 )
{
// iOS while presenting an alertview uses a presening view controller. That controller's view has several subviews. I have picked one
// subview from it which has frame similar to the alertview frame.
UIView *presentedView = [subviews objectAtIndex:1];
UIActivityIndicatorView *customActivityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[customActivityIndicator startAnimating];
customActivityIndicator.center = ACTIVITY_INDICATOR_CENTER;
[presentedView addSubview:customActivityIndicator];
}
}
#end
In - (void)didPresentAlertView:(UIAlertView *)alertView method I have added the subviews to UIAlertView by accessing Presented View Controller's view.
You can find explanation and code example for this on Here
What you were doing was always wrong. You are not allowed to add your own subviews to a UIAlertView. The good news is - in iOS 7, you don't have to! The new custom transition animation mechanism lets you make your own view that behaves just an alert view, but since it is your view, you can put anything you like into it, like this:
Note how the fake "alert view" floats in front of the original view in the screen shot on the right, and dims the screen behind it, just like a real alert view. But it is made up entirely of custom content; a "real" alert view could never contain an image and a switch!
For the code that creates this view, which you can easily adapt to your own purposes, see my github site: https://github.com/mattneub/custom-alert-view-iOS7
I think the root of the problem in iOS7 that Apple changed the UIAlertView appearance mechanism.
From now any show of alertView follows after initiating of two private view controllers
_UIModalItemAppViewController
_UIModalItemsPresentingViewController
In other words, now UIAlertView is not a pure view - it is a part of some complicated collection of view controllers with full view controller life cycle.
But a good news that you can change accessoryView to your customContentView in a standard alert view
[alertView setValue:customContentView forKey:#"accessoryView"];
Note that you must call this before [alertView show].
Here's my view hierarchy: parentView (UIView) has a UIImageView as its subview which in turn has a UIButton as its subview.
left = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"left.png"]];
left.userInteractionEnabled = YES;
[parentView addSubview:left];
back = [UIButton buttonWithType:UIButtonTypeCustom];
[back setImage:[UIImage imageNamed:#"Arrow-left.png"] forState:UIControlStateNormal];
[back addTarget:self action:#selector(back:) forControlEvents:UIControlEventTouchUpInside];
back.showsTouchWhenHighlighted = YES;
[left addSubview:back];
Everything shows up properly but the button does not respond to touches. It does respond if I move its frame out of the UIImageView's frame to somewhere else and set it as a subView to the parentView (UIView). But here's the thing.
Even if I set to parentView's subView the button does not respond if it is within the UIImageView's frame area. The userInteractionEnabled property has been already set to YES for the image view. Any idea what's going on?
UIImageView turns off userInteraction - turn it on and the button will work.
EDIT:
So I used your code almost exactly as written - the one red herring is that you said it all appears fine. For me, the custom button had a frame of 0,0,0,0 so I saw nothing. When I set the frame it all worked perfectly:
UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [UIImage imageNamed:#"46-truck.png"];
assert(image);
[back setImage:image forState:UIControlStateNormal];
[back addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
back.showsTouchWhenHighlighted = YES;
back.frame = (CGRect){ {0,0}, image.size};
NSLog(#"FRAME: %#", NSStringFromCGRect(back.frame) );
[imageView addSubview:back];
So, if you need to probe the superviews during run time to figure out what is what, you can use this code below. [UIView dumpSuperviews:back msg:#"Darn Bark Button"];
#interface UIView (Utilities_Private)
+ (void)appendView:(UIView *)v toStr:(NSMutableString *)str;
#end
#implementation UIView (Utilities_Private)
+ (void)appendView:(UIView *)a toStr:(NSMutableString *)str
{
[str appendFormat:#" %#: frame=%# bounds=%# layerFrame=%# tag=%d userInteraction=%d alpha=%f hidden=%d\n",
NSStringFromClass([a class]),
NSStringFromCGRect(a.frame),
NSStringFromCGRect(a.bounds),
NSStringFromCGRect(a.layer.frame),
a.tag,
a.userInteractionEnabled,
a.alpha,
a.isHidden
];
}
#end
#implementation UIView (Utilities)
+ (void)dumpSuperviews:(UIView *)v msg:(NSString *)msg
{
NSMutableString *str = [NSMutableString stringWithCapacity:256];
while(v) {
[self appendView:v toStr:str];
v = v.superview;
}
[str appendString:#"\n"];
NSLog(#"%#:\n%#", msg, str);
}
+ (void)dumpSubviews:(UIView *)v msg:(NSString *)msg
{
NSMutableString *str = [NSMutableString stringWithCapacity:256];
if(v) [self appendView:v toStr:str];
for(UIView *a in v.subviews) {
[self appendView:a toStr:str];
}
[str appendString:#"\n"];
NSLog(#"%#:\n%#", msg, str);
}
#end
Maybe
parentView.userInteractionEnabled = YES;
Or parent view frame are to small and can`t hold button or image view. Check size of parent view;
I've had this happen before.. I think it was a super view swallowing the event.
I know you've stated that adding it to the parentView only works if it doesn't overlap with the image view. If you disable user interaction on the image view, does the button event trigger consistently when added to the parentView?
You actually need to set userInteractionEnabled = NO to allow the touches to pass through.
Taken from here.
left.userInteractionEnabled = YES;
put this line in the end.
How can I remove the gloss/shine effect from the buttons on navigation bars?
If I customize the navigation bar by using a custom image the buttons are not affected, can I remove the effect from them (the line and glossing), or define a hex color code for the whole button, or even a custom image for them too?
I just went through the process of figuring this out. Basically, you need to create custom stretchable images and use them as the button's background to get rid of the shine. Replacing the back buttons in a UINavigationController is a bit tougher. For that I used a UINavigationControllerDelegate to replace the default back button with my custom button.
Here's some code:
Create a category on UIBarButtonItem that creates your custom button. Here's mine. I use this category to customize both regular bar buttons and back buttons:
#interface UIBarButtonItem (UIBarButtonItem_customBackground)
+ (id) customBarButtonWithTitle:(NSString *)title target:(id)target selector:(SEL)selector;
+ (id) customBackButtonWithTitle:(NSString *)title target:(id)target selector:(SEL)selector;
#end
#implementation UIBarButtonItem (UIBarButtonItem_customBackground)
+ (id) customButtonWithImageNamed:(NSString *)imageName selectedImageNamed:(NSString *)selectedImageName leftCapWidth:(CGFloat)leftCapWidth edgeInsets:(UIEdgeInsets)edgeInsets title:(NSString *)title target:(id)target selector:(SEL)selector {
UIButton* customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
customButton.titleLabel.font = [UIFont boldSystemFontOfSize:12.0f];
customButton.titleLabel.shadowColor = [UIColor colorWithRed:0.0f/255.0f green:0.0f/255.0f blue:0.0f/255.0f alpha:0.25f];
customButton.titleLabel.shadowOffset = CGSizeMake(0.0f, -1.0f);
customButton.titleLabel.lineBreakMode = UILineBreakModeTailTruncation;
customButton.titleEdgeInsets = edgeInsets;
UIImage* navButtonBackgroundImage = [[UIImage imageNamed:imageName] stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:0.0f];
UIImage* navButtonPressedBackgroundImage = [[UIImage imageNamed:selectedImageName] stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:0.0f];
[customButton setBackgroundImage:navButtonBackgroundImage forState:UIControlStateNormal];
[customButton setTitle:title forState:UIControlStateNormal];
[customButton setBackgroundImage:navButtonPressedBackgroundImage forState:UIControlStateHighlighted];
[customButton setBackgroundImage:navButtonPressedBackgroundImage forState:UIControlStateSelected];
CGSize size = CGSizeMake(30.0f, 30.0f);
if (title != nil) {
size = [[NSString stringWithString:title] sizeWithFont:customButton.titleLabel.font];
}
customButton.frame = CGRectMake(0.0f, 0.0f, size.width + 20.0f, 30.0f);
customButton.layer.shouldRasterize = YES;
customButton.layer.rasterizationScale = [[UIScreen mainScreen] scale];
return [[[UIBarButtonItem alloc] initWithCustomView:customButton] autorelease];
}
+ (id) customBarButtonWithTitle:(NSString *)title target:(id)target selector:(SEL)selector {
return [self customButtonWithImageNamed:#"navButtonBG.png"
selectedImageNamed:#"navButtonPressedBG.png"
leftCapWidth:6.0f
edgeInsets:UIEdgeInsetsMake(0.0f, 5.0f, 0.0f, 5.0f)
title:title
target:target
selector:selector];
}
+ (id) customBackButtonWithTitle:(NSString *)title target:(id)target selector:(SEL)selector {
return [self customButtonWithImageNamed:#"backButtonBG.png"
selectedImageNamed:#"backButtonPressedBG.png"
leftCapWidth:12.0f
edgeInsets:UIEdgeInsetsMake(0.0f, 11.0f, 0.0f, 5.0f)
title:title
target:target
selector:selector];
}
#end
Add the button to your UINavigationBar
UIBarButtonItem* logoutButton = [UIBarButtonItem customBarButtonWithTitle:#"Logout" target:self selector:#selector(logout)];
self.navigationItem.rightBarButtonItem = logoutButton;
If you also want to replace the UINavigationController's back buttons, setup a UINavigationControllerDelegate and implement the willShowViewController method like so:
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
if([navigationController.viewControllers count ] > 1) {
UIViewController* backViewController = [navigationController.viewControllers objectAtIndex:(navigationController.viewControllers.count - 2)];
NSString* backText = backViewController.title;
UIBarButtonItem* newBackButton = [UIBarButtonItem customBackButtonWithTitle:backText target:navigationController selector:#selector(popViewControllerAnimated:)];
viewController.navigationItem.leftBarButtonItem = newBackButton;
viewController.navigationItem.hidesBackButton = YES;
}
}
Here are the stretchable images I'm using:
Back button: Pressed:
Regular button: Pressed:
For changing the back button it is not necessary to implement the delegate method uinavigationcontroller.
You only need set the hidesBAckButton property to YES after setting the desired backbutton as #Justin Gallacher explained perfectly.
self.navigationItem.leftBarButtonItem = [UIBarButtonItem customBackButtonWithTitle:#"Back" target:self.navigationController selector:#selector(popViewControllerAnimated:)];
self.navigationItem.hidesBackButton = YES;
you have to use the custom button with images without any gloss effect on the images by which you can get rid of the gloos effect of the button from navbar.
I'm using the following categories code to change
the background image of the navigation bar
#import <Foundation/Foundation.h>
#interface UINavigationBar (CustomImage)
- (void) setBackgroundImage:(UIImage*)image;
- (void) clearBackgroundImage;
#end
#import "UINavigationBar+CustomImage.h"
#implementation UINavigationBar (CustomImage)
- (void) setBackgroundImage:(UIImage*)image {
if (image == NULL) return;
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
[self insertSubview:imageView atIndex:0];
[imageView release];
}
- (void) clearBackgroundImage {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *mySubviews = [self subviews];
for (int i = [mySubviews count] - 1; i >= 0; i--)
{
if ([[mySubviews objectAtIndex:i] isMemberOfClass:[UIImageView class]])
{
[[mySubviews objectAtIndex:i] removeFromSuperview];
return;
}
}
[pool release];
}
#end
And i'm using the following code to generate the custom back button
in my view
UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
[btnBack addTarget:self action:#selector(goBack) forControlEvents:UIControlEventTouchUpInside];
[btnBack setImage:[UIImage imageNamed:#"back.png"] forState:UIControlStateNormal];
UIBarButtonItem *barBtnBack = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
self.navigationItem.leftBarButtonItem = barBtnBack;
[btnBack release];
[barBtnBack release];
But the button most of the time is hidden under the bg image
and some times it randomly appears.
Why is this happening? I'm not sure what's the problem the image is inserted at index 0
so as I understand it is supposed to be behind all the time.
Please help.
Try the following code to change background of the navigation bar in the class where you are loading the navigation bar.
#interface UINavigationBar (MyCustomNavBar)
#end
#implementation UINavigationBar (MyCustomNavBar)
- (void) drawRect:(CGRect)rect
{
UIImage *barImage = [UIImage imageNamed:#"image.png" ];
[barImage drawInRect:rect];
}
#end
Using the method Praveen S suggested you could have a global variable for the next background image name and set it in your viewDidLoad method, then in your draw rect method use the imageName stored in the variable rather than hardcoding it in the draw rect.
You should try creating the button after adding the image.
is there any way to hide an UIButton until the UIImageView is pressed??
When the picture is pressed I need to show the back Button, like it works at the Photo App on the iPhone???
Here is the code of my UIButton:
- (void)viewDidLoad {
[super viewDidLoad];
[self ladeImage];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(10, 10, 40, 40);
[btn addTarget:self action:#selector(goToViewA) forControlEvents:UIControlEventTouchUpInside];
[btn setTitle:#"<<" forState:UIControlStateNormal];
[self.view addSubview:btn];
}
First step : btn.hidden = YES
Then you have to subclass the UIImageView to react to its touchesEnded: event and change the hidden property of your button there. For that, the proper way is to create a protocol (with a viewTouched method). Implement that protocol in the viewController containing your button and you ImageView. Add a delegate propery to the subclassed ImageView (i.e. id<MyCustomProtocol> _delagate;) and assign the view controller to this propery.
btn.hidden = YES;
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"image name"]];
imageView.userInteractionEnabled = YES; // here to enable touch event
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTapGestureRecongizer:)]; // handleTapGestureRecongizer is method will call when tap even fire
[imageView addGestureRecognizer:tap]; // Add Tap gesture recognizer to image view
[tap release], tap = nil;
[self.view addSubview:imageView];
[imageView release], imageView = nil;
Method handlerTapGestureRecognizer:
- (void)handleTapGestureRecongizer:(UITapGestureRecognizer *)gestureRecognizer{
if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
btn.hidden = NO;
}
}
have fun!