any example for creating an iOS custom button? - ios

I would like to create a custom button, which have a custom background image, icon and a label.
It looks very similar like the Twitter button i found:
Any good suggestion is appreciated!

You need to import quartz
#import <QuartzCore/QuartzCore.h>
then to create button like your twitter button simply write this code:
UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeCustom];
yourButton.frame = CGRectMake(50, 50, 100, 50);
yourButton.layer.cornerRadius = 10;
yourButton.clipsToBounds = YES;
yourButton.backgroundColor = [UIColor colorWithRed:57.0/255.0 green:178.0/255.0 blue:235.0/255.0 alpha:1.0];
//if you want to set image as background
//[yourButton setBackgroundImage:[UIImage imageNamed:#"background_image"] forState:UIControlStateNormal]
[yourButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[yourButton setTitle:#"Twitter" forState:UIControlStateNormal];
[yourButton setImage:[UIImage imageNamed:#"twitter_icon"] forState:UIControlStateNormal];

Yes, you can set the button type to "custom" in interface builder. Then you can set the background image, icon, text, and colors to whatever you prefer.
To get rounded corners, you'll have to add some code:
button.layer.cornerRadius = 10; // Change to the value you desire.
button.clipsToBounds = YES;

Related

How to create a button with a clear background

How can I create a UIButton that is transparent other than its image?
I have PNG with a transparent background. I create a button with it, and I get the image in blue tint.
If I set tintColor to clearColor, the tint goes away but so does the black image.
I've been using UIButtonTypeSystem as the button type.
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem] ;
button.frame = rect ;
[button setImage:image forState:UIControlStateNormal] ;
button.backgroundColor = [UIColor clearColor] ; // Does nothing
button.tintColor = [UIColor clearColor] ; // Makes the button go away.
In order to have a transparent button, you should make it of type custom. So your code would become:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = rect ;
[button setImage:image forState:UIControlStateNormal] ;
button.backgroundColor = [UIColor clearColor] ; // This is not necessary, unless you want to specify a color - say [UIColor redColor] - for the button
Since UIButtonTypeCustom does not behave the same way as UIButtonTypeSystem, you should look at the various boolean flags to set specific traits. They would have to be set manually or through Interface Builder. Here are the list of properties.
UIButton *button = [UIButton UIButtonTypeCustom] ;
button.frame = rect ;
[button setImage:image forState:UIControlStateNormal];
you just need to use UIButtonTypeCustom, It's not necessary to set any backgroundColor or tintColor for UIButton.
You need to use UIButtonTypeCustom.
just change one line use UIButtonTypeCustom instead of UIButtonTypeSystem
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom] ;
button.frame = rect ;
[button setImage:image forState:UIControlStateNormal] ;
button.backgroundColor = [UIColor clearColor] ;

Unchangable button width and height

I want to resize a button programatically, but modifying the parameters gives no effect.
btnCancel = [UIButton buttonWithType:102];
[btnCancel setFrame:CGRectMake(22.0f, 7.0f, 40.0f, 40.0f)];
[btnCancel setTitle:#"Anuluj" forState:UIControlStateNormal];
[btnCancel setTintColor:[UIColor redColor]];
[btnCancel addTarget:self action:#selector(cancelTyping) forControlEvents:UIControlEventTouchUpInside];
Any idea why? i can give whatever amount i like to the parameters, but result is the same - width is bounded to text length.
I took your code and tested it in iOS 6.0. This is the final version of what you need to do
Add QuartzCore Library and add this to your header file
#import <QuartzCore/QuartzCore.h>
Now here's your button code with a pic. Play around with width and hight and they will change
UIButton *btnCancel =[UIButton buttonWithType:UIButtonTypeCustom];
[btnCancel setFrame:CGRectMake(22.0f, 7.0f, 80.0f, 80.0f)];
[btnCancel setTitle:#"Anuluj" forState:UIControlStateNormal];
btnCancel.backgroundColor = [UIColor redColor];
btnCancel.layer.borderColor = [UIColor redColor].CGColor;
btnCancel.layer.borderWidth = 0.5f;
btnCancel.layer.cornerRadius = 10.0f;
[btnCancel addTarget:self action:#selector(cancelTyping) forControlEvents:UIControlEventTouchUpInside];
Try to change btnCancel = [UIButton buttonWithType:102]; by btnCancel = [UIButton buttonWithType:UIButtonTypeCustom];
you almost certainly have autolayout turned on. Go into interface builder and turn it off and your code should work
use [UIButton buttonWithType:UIButtonTypeCustom] with appropriate value, button will resize.
UIButtonTypeCustom = 0,
UIButtonTypeRoundedRect,
UIButtonTypeDetailDisclosure,
UIButtonTypeInfoLight,
UIButtonTypeInfoDark,
UIButtonTypeContactAdd

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];

Why is my UIButton.tintColor not working?

My build target is set for IOS5 which is where I understand UIButton.tintColor was introduced...
I have this in my viewDidLoad for the View Controller
[timelineButton setTintColor:[UIColor blackColor]];
[timelineButton setTitle:#"test" forState:UIControlStateNormal];
The text changes properly but the button isn't black?
Thanks!
According to the documentation:
This property is not valid for all button types.
You need to switch your buttonType to another one of these. (Unfortunately, the documentation does not specify which specific button types support this property.)
Make sure your button "type" is set to System. If it is set to Custom it could be the reason the color of your button isn't changing. This is what happened to me and changing the type to System fixed it.
It tint your highlighted State color.
When you tap/click on the UIButton the color specified with tintColor appears as long as you hold the tap/click on the UIButton.
resetButton.tintColor = [UIColor colorWithRed:0.764 green:1.000 blue:0.000 alpha:1.000];
The button is white in normal state.
But if I tap on the button the color turns red, but only then.
IF you need to change the button so it looks like a red or blue one in the UIControlStateNormal then
Change the UIButtonType to UIButtonTypeCustom in Interface Builder or programmatically with
UIButton *resetButton = [UIButton buttonWithType:UIButtonTypeCustom];
Change the attributes on your own and recreate the rounded corners
resetButton.backgroundColor = [UIColor redColor];
resetButton.layer.borderColor = [UIColor blackColor].CGColor;
resetButton.layer.borderWidth = 0.5f;
resetButton.layer.cornerRadius = 10.0f;
As stated in other answers tint does not work for Custom Button types. Make sure you explicitly declare the button type. Do not just use [UIButton alloc] init]
This will work:
UIButton *mybutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[mybutton setImage:[UIImage imageNamed:#"myImage"] forState:UIControlStateNormal];
mybutton.tintColor = [ODTheme blueTintColor];
I found 3 things must be followed.
1. Render image as Default
Go to Images.xcassets > Your Image > Show the Attributes inspector > Render As > Default
2. Make sure your button type is System
3. Now change button's tintColor.
Done.
Today, I also meet this problem. I use delegate to solve it.
[button addTarget:self action:#selector(buttonPress:) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:#selector(buttonPressReset:) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
-(void)buttonPress:(id)sender{
UIButton* button = (UIButton*)sender;
[button setBackgroundColor:[UIColor greenColor]];
NSLog(#"buttonPressed");
}
-(void)buttonPressReset:(id)sender{
UIButton* button = (UIButton*)sender;
[button setBackgroundColor:[UIColor redColor]];
NSLog(#"buttonPressReset");
}
Should try this method:
- (void)setTitleColor:(UIColor *)color
forState:(UIControlState)state
In iOS 13 you can tint the image and then set it to the button:
let coloredImage = UIImage().withTintColor(UIColor.red)
UIButton().setImage(coloredImage, for: .normal)
Simply set your UIButton to type System in Storyboard.
And then in code just use:
myButton.tintColor = UIColor.whiteColor()
If your UIButton type is system then and then only tint colour property is work. So first you need to set your button type to the system then apply tint colour for the specific state.
let btn = UIButton.init(type: .system)
[btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
To change the color of the Button text you can use:
resetButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
Or OBJ-C:
- (void)setTitleColor:(UIColor *)color
forState:(UIControlState)state
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIButton_Class/#//apple_ref/occ/instm/UIButton/setTitleColor:forState:
Simply use:
[yourButton setBackgroundImage:[yourButton.currentBackgroundImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
[yourButton setTintColor:[UIColor blackColor]];
Swift 4 :
yourButton.setTitleColor(UIColor.white, for: .normal)
I couldn't really change the button type to System as I was inheriting from a closed internal library.
So, I changed the appearance API for UIButton
UIView.appearance(whenContainedInInstancesOf: [UIButton.self]).tintColor = .white

How to change backgroundcolor of uibutton programmatically

How would I change the background color of a button to black?
If you want to programatically change the colour of button you will have to make the type of button as custom as :-
UIButton *button = [UIButton buttonWithType:uibuttontypecustom];
note "uibuttontypecustom"
and then you can change backgroung by [btn setBackgroundColor:[UIColor blackColor]]; or you can set a black backgroung image by using steImage method on btn.
Mr/Ms Baiju please review below my code,
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(10, 200, 300, 40);
[button setTitle:#"Button" forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[button setBackgroundColor:[UIColor blackColor]];
[button setImage:[UIImage imageNamed:#"image.png"] forState:UIControlStateNormal];
[self.view addSubview: button];
I think it will help you to set background color and set background image for a button. If you want to set image please change the button type RoundedRect to Custom. I hope it will help you little bit. Thanks.
I think this will help you,
[button setBackgroundColor:[UIColor redColor]];
Use this line of code and try use any color image .
[myButton setImage:[UIImage imageNamed:#"image.png"] forState:UIControlStateNormal];
If anyone wants to know how to make same thing in swift with full code then here it is...Just write this code in your ViewController.swift
import UIKit
class ViewController: UIViewController
{
var firstbutton:UIButton? //firstbutton = Your Button Name
override func viewDidLoad() {
super.viewDidLoad()
self.firstbutton = UIButton.buttonWithType(UIButtonType.Custom) as? UIButton
self.firstbutton!.frame = CGRectMake(100, 200, 100, 100)
//This Line is used for color of your button
self.firstbutton!.backgroundColor = UIColor.redColor()
self.view.addSubview(firstbutton!)
}
//This section is used to bring the button in front of everything on the view
override func viewDidAppear(animated: Bool) {
self.view.bringSubviewToFront(self.firstbutton!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
in your XIB drag and drop a button. got to button properties in your right hand side and set button type to custom. (Or you can do than in code too). In your .h file create UIButton * btn; and bind it to the XIB.
Then go to .m file and in viewdidload method right this code.
[btn setBackgroundColor:[UIColor blackColor]];
Thanks :)
Change the layer colour e.g. self.btn.layer.backgroundColor = [UIColor redColor].CGColor;

Resources