I have a Bar Button Item and I wanna set a background image for it.
Both the button and the background image are set in the xib file.
Here how it looks like:
As you can see the image doesn't covers the whole width of the button.
Now, I tried setting up as background a larger image and here is how the result looks like:
The button gets larger itself and still the image doesn't fits its size.
Anyone any idea of how to make this work?
Try this, it works very well in these cases:
UIImage *btnImg = [UIImage imageNamed:#"myImg.png"];
UIImage *btnGreyImg = [btnImg stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[myBtn setBackgroundImage:btnGreyImg forState:UIControlStateNormal];
Of course, you can write this in one line or two lines, I just wanted to show it clearly...
In my case, I made the outlet of the BarButtonItem as backBack and in viewDidLoad: method I wrote this code:
UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
btnBack.frame = CGRectMake(0, 0, 250, 300);
[btnBack setImage:[UIImage imageNamed:#"sample.png"] forState:UIControlStateNormal];
[btnBack addTarget:self action:#selector(callMethod:) forControlEvents:UIControlEventTouchUpInside];
backButton.customView = btnBack;
I hope this is helpful in your case.
Related
I am trying to use a button in place of the title on a UINavigationBar. I have been successful in getting the button to display with a custom image, but I am having a hard time figuring out how to resize it. I have tried a few things, including:
UIButton *titleButton = [[UIButton alloc]init];
UIImage *settingsButtonImage = [UIImage imageNamed:#"settingsButton2X.png"];
[titleButton addTarget:self action:#selector(settingsButtonPress:) forControlEvents:UIControlEventTouchDown];
[titleButton setBackgroundImage:settingsButtonImage forState:UIControlStateNormal];
[titleButton setFrame:CGRectMake(0, 0, 20, 20)];
self.navigationItem.titleView = titleButton;
This works great, except the resulting image in the navigation bar is only resized in the y-direction, resulting a smooshed appearance (unfortunately I can't post an image to show that because I don't have a reputation - you might be able to see it here: http://i.stack.imgur.com/fNh7O.png)
I can use a 20 x 20px image and it displays correctly, but that looks pixelated on the retina display.
So my main question is: what is the best way to add a button to the title area of a UINavigationBar? What is the best pixel size for an image for this button which will look sharp on both the older iphone screens, and the new retina displays? (clearly there is something about the pixel size of the images that I'm just not grasping - I thought that starting with a 40x40px or 60x60px image would be best).
Thanks for the help!
Why don't you try something like this :-------
UIButton *titleButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
UIImage *settingsButtonImage = [UIImage imageNamed:#"settingsButton2X.png"];
[titleButton addTarget:self action:#selector(settingsButtonPress:) forControlEvents:UIControlEventTouchDown];
[titleButton setBackgroundImage:settingsButtonImage forState:UIControlStateNormal];
titleButton.center=self.navigationController.navigationBar.center;
titleButton.center=CGPointMake(titleButton.center.x, self.navigationController.navigationBar.frame.size.height/2);
[self.navigationController.navigationBar addSubview:titleButton];
I created a UIBarButton programmatically with the following code:
UIButton * rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
[rightButton setFrame:CGRectMake(0, 0, 81, 30)];
[rightButton setBackgroundColor:[UIColor clearColor]];
rightButton.layer.borderColor = [UIColor blackColor].CGColor;
rightButton.layer.borderWidth = 0.5f;
rightButton.layer.cornerRadius = 5.0f;
rightButton.titleLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:12];
[rightButton setTitleShadowColor:[UIColor blackColor] forState:UIControlStateNormal];
[rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//set text according to sign in status
if (signIn) {
[rightButton setTitle:#"5 votes left" forState:UIControlStateNormal];
} else {
[rightButton setTitle:#"Sign in" forState:UIControlStateNormal];
}
UIBarButtonItem * rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
self.navigationItem.rightBarButtonItem = rightBarButton;
The obtained button has the desired aspect but now what I need is that when the status of the button is highlighted there should be a gradient effect fading to black to let the user know that he has pressed the button, because right now when I pressed the button, nothing happens to the view so the user has no way to know that he has pressed the button.
I want to explore a choice that does NOT involve setting the background images for the desired states because the text of the button can change dynamically according to the app configurations so I need to do this entirely by code.
Although this won't directly answer your question, it may help. I had to create some graphics for a button dynamically and came up with a method using core graphics to create my button image. It gives me the flexibility to change to appearance parametrically in the code.It draws the button image in an abstract graphics context and then converts the result into an image that I can use for my button. YOu might get enough out of my explanation that you can try it yourself for your needs.
Subclass UIButton and add a CALayer or CAGradientLayer to achieve the highlight effect that you want. Set the initial state of the highlight layer to hidden. Override setHighlighted: with something like:
- (void) setHighlighted:(BOOL)highlight {
highlightLayer.hidden = !highlight;
[super setHighlighted:highlight];
}
I have a UIToolbar which I am trying to put some custom UIBarButtonItems on. However, when I use the code below, the button shows up with NO border.
UIImage *cameraRollButtonImage = [UIImage imageNamed:#"Flash.png"];
UIButton *cameraRollButton = [UIButton buttonWithType:UIButtonTypeCustom];
[cameraRollButton setImage:cameraRollButtonImage forState:UIControlStateNormal];
cameraRollButton.frame = CGRectMake(0.0, 0.0, cameraRollButtonImage.size.width, cameraRollButtonImage.size.height);
// Initialize the UIBarButtonItem
cameraRollButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cameraRollButton];
[cameraRollButtonItem setStyle:UIBarButtonItemStyleBordered];
//Add the Buttons to the toolbar
NSArray *toolbarItems = [NSArray arrayWithObject:cameraRollButtonItem];
[self.cameraTabBar setItems:toolbarItems];
This displays the button just fine, however, there is NO button border (like standard the UIBarButtonItem). So the line [cameraRollButtonItem setStyle:UIBarButtonItemStyleBordered]; doesn't seem to do anything.
Does anyone have any experience with this?
I would like to be able to eventually rotate the image in the button when the device orientation is changed (keeping the toolbar static), so simply adding an image to the UIBarButtonItem doesn't work; I need to get this to work with by using the customView property.
Many thanks!
Brett
Have you considered creating your own button image with a border? You can use it as the backgroundImage of a UIButton:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:_backgroundImage_ forState:UIControlStateNormal];
// So that the button does not gray out when disabled
[button setBackgroundImage:_backgroundImage_ forState:UIControlStateDisabled];
[button setImage:_cameraImage_ forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, 125, 30);
You could then use button with initWithCustomView:.
The PSD file here might give you an overview of how to create your own button.
I must have overlooked something completely obvious?? but my button displays its image and size correctly, but I simply can't get the Title to show up.
I did a really simple test, the Title does not even show up when I do this:
CGRect frameBtn = CGRectMake(160.0f, 150.0f, 144.0f, 42.0f);
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:#"left_halfscreen_button.png"] forState:UIControlStateNormal];
[button setTitle:#"Hello" forState:UIControlStateNormal];
[button setFrame:frameBtn];
NSLog(#"Title:%#", [button currentTitle]);
//prints "Title:Hello
[self addSubview:button];
I have a factory class that generates custom buttons for me and I thought I messed some detail up there, so I moved the above code directly into my UIView, the title is still blank.
Is this a bug or am I simply missing something right in front of my eyes.
Thank you for the extra set of eyes:)
Image overrides title, you need to make the image a background image to show the title.
[button setBackgroundImage:[UIImage imageNamed:#"left_halfscreen_button.png"]
forState:UIControlStateNormal];
I just hab spome quite similar problem... Just set the title color, I guess the current one is white ;)
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
I found the problem!
It's not Image overriding the title. It is being push off frame by the image.
Try use this:
[btn setTitleEdgeInsets:UIEdgeInsetsMake(0.0, -img.size.width, 0.0, 0.0 )];
Hope it helps!
When you use UIButton, button uses some built-in size for its frame.
You should set the frame:
button.frame = CGRectMake(0, 0, width, height);
or even better and comfortable:
[button sizeToFit];
I had a similar problem that the title was not shown. I forgot to set the frame property:
//set the position of the button
button.frame = CGRectMake(100, 170, 100, 30);
I thought to be clever and just put an transparent UIButton over an UIImageView with the exact frame size, so that I can wire it up easily with any event I like, for example TouchUpInside, and make it call a action method of an view controller when the user touches it. Well, it works until alpha is below 0.1f. If I do 0.01f, it will not work. So to get it work, when looking a long time on the screen, you'll see that 0.1f of alpha shining through. And that's totally disgusting ;)
It seems like iPhone OS trys to be clever and won't catch events on the button if it's visually not there. Any idea how to solve that?
Sure I could make a subclass of UIImageView and implement touchesBegan:... etc., but it doesn't feel really elegant. I mean...when I want to hyperlink an image on the web, I would never want create my own HTML element for that image, just to wire it up to an url when it's clicked. That just doesn't make a lot of sense to me.
You should be able to set the button's 'Type' to Custom in Interface Builder, and it will not display any text or graphical elements over the UIImageView. This way, you don't need to adjust the alpha. If the view is built from code, use:
button = [UIButton buttonWithType:UIButtonTypeCustom];
In addition to UIButtonTypeCustom, I set the button text colors to the following:
[button setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
[button setTitleShadowColor:[UIColor clearColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor clearColor] forState:UIControlStateHighlighted];
[button setTitleShadowColor:[UIColor clearColor] forState:UIControlStateHighlighted];
The best way of doing this is:
myButton.hidden = YES;
You can't use the buttonType property because it is a read only property. Only way to use it is when creating your button dynamically.
i also beleive you can assign an image to a button.
The image can take up the entire frame and can also have no other artifacts of the buttone if you set it up right.
check out the Property
UIButtonInstance.currentImage
That way you are not hogging your resources with elements that are essentially already there.
You can hide a button (or any object) and keep it active by adding a mask to its layer. The button will be invisible but will still catch events.
let layer = CAShapeLayer()
layer.frame = .zero
myButton.layer.mask = layer
Jasons answer above is nearly correct, but setting the button type is not possible. So to programmatically create an empty button, use this code:
UIButton* myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame=frame;
[self.view addSubview:myButton];
This is what i did but with using a subclass of UIButton which i later found out should not be subclassed as per the net. My subclass was called Points
Points *mypoint=[Points buttonWithType:UIButtonTypeCustom];
then if you have an image you want to add to the button :
[mypoint setImage:imageNamed:#"myimage"] forstate: UIControlStateNormal];
if you dont add this image then the button will be invisible to the user but should respond to touch. Thats how i created a hotspot on my imageView inorder to have it respond to user interaction.
It's the only way I found...
[yourButton setImage:[UIImage imageNamed:#"AnEmptyButtonWithTheSameSize.png"] forState:UIControlStateNormal];
Take care of the image. It must be .png
Custom UIButtons respond to user interactions unless their alpha is set to 0. Put a custom UIButton on top of your imageView and connect to buttonPressed action. I have also set an additional highlighted image for my UIView, now it really behaves like a UIButton. First I have defined a duration for the UIView for staying highlighted:
#define HIGHLIGHTED_DURATION 0.1
Then set the image view highlighted if the button is pressed and start a timer to keep it highlighted for that duration. Do not forget to set the highlighted image for your imageview.
- (IBAction)buttonPressed:(id)sender {
[_yourImageView setHighlighted:YES];
_timer = [NSTimer scheduledTimerWithTimeInterval:HIGHLIGHTED_DURATION
target:self
selector:#selector(removeHighlighted)
userInfo:nil
repeats:NO];
}
And simply undo highlighting when the timer finishes:
-(void) removeHighlighted{
_yourImageView.highlighted = NO;
}
lazyImageView = [[UIImageView alloc] init];
button=[[UIButton alloc]init];
[UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(aMethodForVideo:)
forControlEvents:UIControlEventTouchUpInside];
[button setBackgroundImage:[UIImage imageNamed:#"BackTransparent.png"] forState:UIControlStateHighlighted];
[button setTitle:#"" forState:UIControlStateNormal];
lazyImageView.frame=CGRectMake(x, y, w, h);
button.frame=CGRectMake(x, y, w, h);
Set frame of button and Image both have same frame .I use this code and working fine.Also set button background image forState:UIControlStateHighlighted so when you click on that when you see the click effect.
I managed to do it using the following code.
If the iPad is landscape the button will be located in the top right of the screen.
UIButton *adminButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
adminButton.frame = CGRectMake(974.0f, 0.0f, 50.0f, 50.0f);
[adminButton setBackgroundColor:[UIColor clearColor]];
[adminButton setTag:1];
[adminButton addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:adminButton];
Pressing the 'adminButton' will run the following function:
- (void)buttonPressed:(id)sender {
int buttonId = ((UIButton *)sender).tag;
switch(buttonId) {
case 1:
NSLog (#"Admin button was pressed");
break;
case 2:
//if there was a button with Tag 2 this will be called
break;
default:
NSLog(#"Key pressed: %i", buttonId);
break;
}
}