How to programmatically set my UIButton image to 'redraw'? - ios

I am using some vector graphics (.png) for my app. In photoshop, I can zoom in and always see a perfectly crisp boundary for simple geometric shapes, like circles. However, on my iPhone, my same graphics look jaggedy and rough. I found that if I change the image fill type to redraw', this helps the problem.
So, can someone please confirm if using redraw is the correct solution in this situation? Also, how can I make the image for a programmatically defined button use 'redraw' instead of the default (which I think is 'fill')?
Here is my current button's code:
UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn1 setTitle:#"Cool title" forState:UIControlStateNormal];
[btn1 setFrame:CGRectMake(7, 7, 150, 160)];
[btn1 setImage:[UIImage imageNamed:#"myGraphic.png"] forState:UIControlStateNormal];
[btn1 addTarget:self action:#selector(selectFav) forControlEvents:UIControlEventTouchUpInside];
[_scroller addSubview:btn1];

remove this line:
UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
add this line:
UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
set content mode:
[btn1 setContentMode:UIViewContentModeRedraw];
Hope this answers all your concerns!

Related

Why image is strectching

I have UIbutton with image. I created small image using photoshop with png format. But when it displays in mobile i'm getting stretching. This image is stretching for iphone4 & iphone5 screen sizes. But navigation bar back button text is not stretching. See the difference between back and search button text.
searchbtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//searchbtn = [UIButton buttonWithType:UIButtonTypeCustom];
searchbtn addTarget:self action:#selector(search:) forControlEvents:UIControlEventTouchUpInside];
//[searchbtn setImage:[UIImage imageNamed:#"searchinside_iphone.png"] forState:UIControlStateNormal];
[searchbtn setImage:[UIImage imageNamed:#"searchinside_iphone.png"] forState:UIControlStateNormal];
[searchbtn setTitle:#"Search" forState:UIControlStateNormal];
searchbtn.frame = CGRectMake(200, 5, 140/2, 60/2);

button on a map is not getting displayed?

In my app, I have a map view, I want to display a custom button on the map, if a place the button, it gets displayed but, if I place a background image for the image, it is not getting printed.
UIButton *customButton = [UIButton buttonWithType: UIButtonTypeCustom];
[customButton setBackgroundImage:[UIImage imageNamed:
#"Button_Default.png"]
forState:UIControlStateNormal];
[customButton setBackgroundImage:[UIImage imageNamed:
#"Button_Highlighted.png"]
forState:UIControlStateHighlighted];
[customButton setFrame:CGRectMake(60, 100, 200, 40)];
[self.view addSubview:customButton];
I have also tried changing the last line as
[mapView addSubview:customButton];
You have to make sure that you have the images added to your project, may be in resource folder & the file name you are using in your code should not be misspelled (quiet often people do typo mistakes like using keyword imagedNamed instead of imageNamed).

buttons turn blue when backgroundimage is set

I have a few buttons and when I set a picture as background the icons turn blue, for example:
[self.button setImage:[UIImage imageNamed:#"image.png"] forState:UIControlStateNormal];
All pictures are black and white, so I don't understand why they change their color when I set them as a backgroundimage.
Make sure to init the button as a "UIButtonTypeCustom"
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
Then if you want the whole button to be an image, you use:
[button setImage:[UIImage imageNamed:#"image.png"] forState:UIControlStateNormal];
... Or if you want to have the image as the background, and still see the "title", you use:
[button setBackgroundImage:[UIImage imageNamed:#"image.png"] forState:UIControlStateNormal];
First do
self.button = [UIButton buttonWithType:UIButtonTypeCustom];
and then set image
[self.button setImage:[UIImage imageNamed:#"image.png"] forState:UIControlStateNormal];

UIButton Image + Text IOS

I need a UIButton with image & text. Image should be in the top & text comes under the image both should be clickable.
I see very complicated answers, all of them using code. However, if you are using Interface Builder, there is a very easy way to do this:
Select the button and set a title and an image. Note that if you set the background instead of the image then the image will be resized if it is smaller than the button.
Set the position of both items by changing the edge and insets. You could even control the alignment of both in the Control section.
You could even use the same approach by code, without creating UILabels and UIImages inside as other solutions proposed. Always Keep It Simple!
EDIT: Attached a small example having the 3 things set (title, image and background) with correct insets
I think you are looking for this solution for your problem:
UIButton *_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button setFrame:CGRectMake(0.f, 0.f, 128.f, 128.f)]; // SET the values for your wishes
[_button setCenter:CGPointMake(128.f, 128.f)]; // SET the values for your wishes
[_button setClipsToBounds:false];
[_button setBackgroundImage:[UIImage imageNamed:#"jquery-mobile-icon.png"] forState:UIControlStateNormal]; // SET the image name for your wishes
[_button setTitle:#"Button" forState:UIControlStateNormal];
[_button.titleLabel setFont:[UIFont systemFontOfSize:24.f]];
[_button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; // SET the colour for your wishes
[_button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted]; // SET the colour for your wishes
[_button setTitleEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, -110.f, 0.f)]; // SET the values for your wishes
[_button addTarget:self action:#selector(buttonTouchedUpInside:) forControlEvents:UIControlEventTouchUpInside]; // you can ADD the action to the button as well like
...the rest of the customisation of the button is your duty now, and don't forget to add the button to your view.
UPDATE #1 and UPDATE #2
or, if you don't need a dynamic button you could add your button to your view in the Interface Builder and you could set the same values at there as well. it is pretty same, but here is this version as well in one simple picture.
you can also see the final result in the Interface Builder as it is on the screenshot.
Xcode-9 and Xcode-10 Apple done few changes regarding Edge Inset now, you can change it under size-inspector.
Please follow below steps:
Step-1:
Input text and select image which you want to show:
Step-2:
Select button control as per your requirement as shown in below image:
Step-3:
Now go-to size inspector and add value as per your requirement:
swift version:
var button = UIButton()
newGameButton.setTitle("Новая игра", for: .normal)
newGameButton.setImage(UIImage(named: "energi"), for: .normal)
newGameButton.backgroundColor = .blue
newGameButton.imageEdgeInsets.left = -50
In my case, I wanted to add UIImage to the right and UILabel to the left. Maybe I can achieve that by writing code (like the above mentioned), but I prefer not to write code and get it done by using the storyboard as much as possible. So this is how did it:
First, write down something in your label box and select an image that you want to show:
And that will create a button looking like this:
Next, look for Semantic and select Force Right-to-Left (If you don't specify anything, then it will show the image to the left and label to the right like the above image):
Finally, you'll see UIImage to the right and UILabel to the left:
To add space between a label and an image, go to the Size inspector and change those values depending on your requirement:
That's it!
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.imageView.image = [UIImage imageNamed:#"your image name here"];
button.titleLabel.text = #"your text here";
but following code will show label above and image in background
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.background.image = [UIImage imageNamed:#"your image name here"];
button.titleLabel.text = #"your text here";
There is no need to use label and button in same control because UIButton has UILabel and UIimageview properties.
Use this code:
UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[sampleButton setFrame:CGRectMake(0, 10, 200, 52)];
[sampleButton setTitle:#"Button Title" forState:UIControlStateNormal];
[sampleButton setFont:[UIFont boldSystemFontOfSize:20]];
[sampleButton setBackgroundImage:[[UIImage imageNamed:#"redButton.png"]
stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal];
[sampleButton addTarget:self action:#selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sampleButton]
You should create custom imageview for image and custom label for text and you add to your button as subviews. That's it.
UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeCustom];
yourButton.backgroundColor = [UIColor greenColor];
yourButton.frame = CGRectMake(140, 40, 175, 30);
[yourButton addTarget:self action:#selector(yourButtonSelected:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:yourButton];
UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, yourButton.frame.size.width, yourButton.frame.size.height/2)];
imageView1.image =[UIImage imageNamed:#"images.jpg"];
[yourButton addSubview:imageView1];
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, yourButton.frame.size.height/2, yourButton.frame.size.width, yourButton.frame.size.height/2)];
label.backgroundColor = [UIColor greenColor];
label.textAlignment= UITextAlignmentCenter;
label.text = #"ButtonTitle";
[yourButton addSubview:label];
For testing purpose, use yourButtonSelected: method
-(void)yourButtonSelected:(id)sender{
NSLog(#"Your Button Selected");
}
I think it will be helpful to you.
Use this code:
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.imageView.frame=CGRectMake(0.0f, 0.0f, 50.0f, 44.0f);///You can replace it with your own dimensions.
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 35.0f, 50.0f, 44.0f)];///You can replace it with your own dimensions.
[button addSubview:label];
I encountered the same problem, and I fix it by creating a new subclass of UIButton and overriding the layoutSubviews: method as below :
-(void)layoutSubviews {
[super layoutSubviews];
// Center image
CGPoint center = self.imageView.center;
center.x = self.frame.size.width/2;
center.y = self.imageView.frame.size.height/2;
self.imageView.center = center;
//Center text
CGRect newFrame = [self titleLabel].frame;
newFrame.origin.x = 0;
newFrame.origin.y = self.imageView.frame.size.height + 5;
newFrame.size.width = self.frame.size.width;
self.titleLabel.frame = newFrame;
self.titleLabel.textAlignment = UITextAlignmentCenter;
}
I think that the Angel García Olloqui's answer is another good solution, if you place all of them manually with interface builder but I'll keep my solution since I don't have to modify the content insets for each of my button.
Make UIImageView and UILabel, and set image and text to both of this....then Place a custom button over imageView and Label....
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"search.png"]];
imageView.frame = CGRectMake(x, y, imageView.frame.size.width, imageView.frame.size.height);
[self.view addSubview:imageView];
UILabel *yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y,a,b)];
yourLabel.text = #"raj";
[self.view addSubview:yourLabel];
UIButton * yourBtn=[UIButton buttonWithType:UIButtonTypeCustom];
[yourBtn setFrame:CGRectMake(x, y,c,d)];
[yourBtn addTarget:self action:#selector(#"Your Action") forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:yourBtn];
It's really simple,just add image to background of you button and give text to titlelabel of button for uicontrolstatenormal.
That's it.
[btn setBackgroundImage:[UIImage imageNamed:#"img.png"] forState:UIControlStateNormal];
[btn setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
[btn setTitle:#"Click Me" forState:UIControlStateNormal];

UIButton doesn't show image

I have a UITableViewCell that I'm adding five UIButtons to. I programmatically create the buttons, add an action, and an image. The buttons are placed in the correct spot, the action works, and the tag is set, but they are clear. The images do not show.
This is what I'm using to create one of the buttons and add them to the cell, this code is in the tableView:cellForRowAtIndexPath: :
if ([[self.compCompletion objectForKey:#"Key" isEqualToString:#"YES"]) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(11, 6, 21, 21);
button.tag = 1;
[button addTarget:self action:#selector(changeCompStatus:) forControlEvents:UIControlEventTouchUpInside];
[button setImage:[UIImage imageNamed:#"Comp-Completed.png"] forState:UIControlStateNormal];
[button setContentMode:UIViewContentModeScaleToFill];
[cell.contentView addSubview:button];
}
else {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(11, 6, 21, 21);
button.tag = 1;
[button addTarget:self action:#selector(changeCompStatus:) forControlEvents:UIControlEventTouchUpInside];
[button setImage:[UIImage imageNamed:#"Comp-Uncompleted.png"] forState:UIControlStateNormal];
[button setContentMode:UIViewContentModeScaleToFill];
[cell.contentView addSubview:button];
}
I've tried adding: [button setEnabled:YES];, [button setHidden:NO];, and [button setNeedsDislpay]; to the process with no luck. How do I get the button to display the image?
EDIT:
My image exists, the UIImage created, and I can pull the UIImage out of the UIButton and save it to a file. I've gone through each property of the UIButton that controls appearance and changed them. I also tried an empty UIButton of type UIButtonTypeRoundedRect and UIButtonTypeAddContact. I'm now believe that this has something to do with the UITableViewCell not liking UIButtons, or how I'm adding the UIButton to the UITableViewCell.
Make sure that you have checked your project as Target Membership when copying the files. It helped me solve the problem.
My mistake was dragging the images into an images.xcassets file that was part of a pod, NOT the main project. It showed fine in the storyboard, but did not appear in the app.
In case anyone is still looking for an answer: Once the image was in assets.xcassets then I needed to include it in the "copy bundle resources" areas of the Build Phases part of the Target. Then I also had to set a transparent color so that it wasn't obscured.
project->targets->build phases->copy bundle resources-> "+" -> "add other"->select the image in the finder.
Check whether your images exist and are imported. Also it looks to me that besides of the image name the code is identical. A bit cleaner as:
UIImage *buttonImage;
if ([[self.compCompletion objectForKey:#"Key" isEqualToString:#"YES"]) {
buttonImage = [UIImage imageNamed:#"Comp-Completed.png"];
} else {
buttonImage = [UIImage imageNamed:#"Comp-Uncompleted.png"];
}
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(11, 6, 21, 21);
button.tag = 1;
[button addTarget:self action:#selector(changeCompStatus:) forControlEvents:UIControlEventTouchUpInside];
[button setImage:buttonImage forState:UIControlStateNormal];
[button setContentMode:UIViewContentModeScaleToFill];
[cell.contentView addSubview:button];
Can it definitely find the images? Are they included in the project?
Just to test, try using an image you've already used somewhere else instead of Comp-Completed.png - if that works, you know that the problem is that it's failing to find that file.
UIImage * normalImage = [UIImage imageNamed:#"Comp-Uncompleted.png"];
UIImage * selectedImage = [UIImage imageNamed:#"Comp-Completed.png"];
UIButton *button = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
button.frame = CGRectMake(11, 6, 21, 21);
button.tag = 1;
[button addTarget:self action:#selector(changeCompStatus:) forControlEvents:UIControlEventTouchUpInside];
[button setImage:normalImage forState:UIControlStateNormal];
[button setImage:selectedImage forState:UIControlStateSelected];
[cell.contentView addSubview:button];
if ([[self.compCompletion objectForKey:#"Key" isEqualToString:#"YES"]) {
button.selected = YES;
} else {
button.selected = NO;
}
I know it is an old post but I came across the same problem and it was due to isHidden and isUserInteractionEnabled set to values to hide the button.
You have to be careful when to set them to YES or NO.
In case anyone is looking for answer, double check if you have copied the image to Assets.xcassets in project directory not in pods directory.
Second I used render as original image in Assets.xcassets image properties

Resources