UIButton - Lead Text with Icon - ios

I am trying to figure out a solution to creating a UIButton, with centred text which has a UIImage (icon) leading the text, so its sites just in front of the button title.
I, however am struggling to think up a way of doing this as you cannot retrieve the position of the text. Any thoughts? This must be a fairly common thing to do.

Use this code
UIButton *scoreButton=[UIButton buttonWithType:UIButtonTypeCustom];
scoreButton.frame=CGRectMake(0,0,100, 100);
//scoreButton.contentEdgeInsets=UIEdgeInsetsMake(0, 0, 0, 2);
scoreButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
scoreButton.titleLabel.font=[UIFont boldSystemFontOfSize:13];
[scoreButton setTitleColor:[UIColor colorWithRed:0.9411 green:0.5647 blue:.2916 alpha:YES] forState:UIControlStateNormal];
[scoreButton addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside];
UIImageView *scoreButtonImageView=[[UIImageView alloc]init];
scoreButtonImageView.frame=CGRectMake(0,35,30 ,30);
scoreButtonImageView.image=[UIImage imageNamed:#"leaderboard_score_button.png"];
[scoreButton addSubview:scoreButtonImageView];
Use UIEdgeInsetsMake to set your text start and end points.
In this way your image will be on the extreme left hand side and you can write text after the image

Create a UIView subclass that has a UIImageView and UILabel. Position the label to the right of the image view within this view. Add this view to your button and position it horizontally and vertically centred.

I think , it will help you. Always careful with setImage: and setBackgroundImage:
UIButton *yourBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[yourBtn setBackgroundImage:bgImage forState:UIControlStateNormal];
[yourBtn setBackgroundImage:bgImage forState:UIControlStateHighlighted];
[yourBtn setTitle:titleString forState:UIControlStateNormal];

Use following method :
UIImageView *yourPlusSign = [UIImageView alloc]initWithImage:[UIImage imageNamed:#"yourPlusSignImageTitle"];
yourPlusSign.frame = CGRectMake(x, y, width, height);//choose values that fit properly inside the frame of your baseButton
//or grab the width and height of yourBaseButton and change accordingly
yourPlusButton.contentMode=UIViewContentModeScaleAspectFill;//or whichever mode works best for you
[yourBaseButton addSubview:yourPlusSign];
Here is Ref : Add an image inside UIButton as an accesory

you can also subclass UIButton it is a better way to do it.

If you use font images like me you can do it with a NSParagraphStyle
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setAlignment:NSTextAlignmentCenter];
UIFont *font1 = [UIFont fontWithName:#"Avenir-Roman" size:14.0];
UIFont *font2 = [UIFont fontWithName:#"Icon-Moon" size:12.0];
NSDictionary *fontSyle1 = #{NSUnderlineStyleAttributeName:#(NSUnderlineStyleNone),
NSFontAttributeName:font1,
NSParagraphStyleAttributeName:style};
NSDictionary *fontStyle2 = #{NSUnderlineStyleAttributeName:#(NSUnderlineStyleNone),
NSFontAttributeName:font2,
NSParagraphStyleAttributeName:style};
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] init];
[attString appendAttributedString:[[NSAttributedString alloc] initWithString:[IcoMoon iconString:k12_ADD_NOTE] attributes:fontStyle2]];
[attString appendAttributedString:[[NSAttributedString alloc] initWithString:#" Add Note" attributes:fontStyle1]];
[_addNewBtn setAttributedTitle:attString forState:UIControlStateNormal];
[[_addNewBtn titleLabel] setNumberOfLines:0];
_addNewBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
_addNewBtn.layer.borderWidth = 1;
[_addNewBtn setBackgroundColor:[UIColor whiteColor]];
[_addNewBtn setTintColor:[UIColor darkGrayColor]];
This where you can get icon fonts https://icomoon.io/
This part is part of a way to convert char's to strings
[IcoMoon iconString:k12_ADD_NOTE]
you can find out more by going to https://github.com/sebastienwindal/IOSIcoMoon

Related

sizeToFit is placing padding around very short strings

I have a UIButton on which I call sizeToFit after settings its title. In cases where the title text is very short (probably < 20pt), the button is taking on a few points of padding on the left and right. For anything longer, the padding disappears. It is as if the button has an internal minimum width that is respected when sizeToFit is called. Does anyone know how to prevent this padding?
This works, Just change the string to whatever and and enjoy the resizing miracle.
NSString * helloKitty = #"I love cats";
UIButton * ss = [UIButton buttonWithType:UIButtonTypeCustom];
[ss setTitle:helloKitty forState:UIControlStateNormal];
[[ss titleLabel] setFont:[UIFont systemFontOfSize:14]];
[ss setBackgroundColor:[UIColor pink] forState:UIControlStateNormal];
CGSize strSizer = [helloKitty sizeWithAttributes:#{NSForegroundColorAttributeName:[UIColor blackColor],
NSFontAttributeName:[UIFont systemFontOfSize:14]}];
[ss setFrame:CGRectMake(100,200,strSizer.width, strSizer.height)];
[self.view addSubview:ss];

Shadow on UIButton text only (not background)

I have a set of UIButtons with background colors. when the user taps one, I want only the button's text to have a shadow all around it (to show that it has been selected). However, when I add the shadow, the shadow appears over the whole button (background and all), and not just the text. Is there an easier workaround to this than just adding a UILabel over a blank button?
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
...
[button setBackgroundColor:[UIColor blueColor]];
[button.layer setShadowRadius:8.0];
[button.layer setShadowColor:[[UIColor orangeColor] CGColor]];
[button.layer setShadowOpacity:0];
...
Here is the simple way to add shadow to the button title with shadow radius property available in Objective-C:
#import <QuartzCore/QuartzCore.h>
button.titleLabel.layer.shadowOffset = CGSizeMake(2.0, 2.0);
button.titleLabel.layer.shadowColor = [UIColor colorWithWhite:0.1 alpha:0.7].CGColor;
button.titleLabel.layer.shadowRadius = 2.0;
button.titleLabel.layer.shadowOpacity = 1.0;
button.titleLabel.layer.masksToBounds = NO;
Swift ..
Say you override the UIButton class ..
titleLabel!.layer.shadowColor = UIColor.black.cgColor
titleLabel!.layer.shadowOffset = CGSize(width: -0.5, height: 0.5)
titleLabel!.layer.shadowOpacity = 1.0
titleLabel!.layer.shadowRadius = 0
titleLabel!.layer.masksToBounds = false
You need to use setTitleShadowColor: forState: and shadowOffset property of UIButton.
below code will add shadow only to button label whenever user tap on button.
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button setBackgroundColor:[UIColor blueColor]];
button.frame = CGRectMake(50, 70, 200, 100);
[button setTitle:#"Test Button" forState:UIControlStateNormal];
[button.titleLabel setFont:[UIFont systemFontOfSize:45]];
[button setTitleShadowColor:[UIColor redColor] forState:UIControlStateHighlighted];
[button.titleLabel setShadowOffset:CGSizeMake(2.0, 2.0)];
Hope this will help.
Just set the shadow on the titleLabel property of the UIButton rather than what you're doing now.
eg
button.titleLabel.shadowColor = ((selectionState) ?[UIColor orangeColor] : [UIColor clearColor] );
button.titleLabel.shadowOffset = CGSizeMake (1.5,1.5);
For 2018
This does not work. Use the answer of #Userich
One way to do this is to use attributed strings for the normal and highlighted titles. You can create an NSShadow object, and assign that as the value for the NSShadowAttributeName. This gives you control over the properties of the shadow. To keep the title from dimming, you should set the button type to Custom instead of System.
- (void)viewDidLoad {
[super viewDidLoad];
NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowColor = [UIColor darkGrayColor];
shadow.shadowOffset = CGSizeMake(2, 2);
shadow.shadowBlurRadius = 2;
NSString *titleString = #"Title";
NSAttributedString *normalTitle = [[NSAttributedString alloc] initWithString:titleString];
NSAttributedString *highlightedTitle = [[NSAttributedString alloc] initWithString:titleString attributes:#{NSShadowAttributeName:shadow}];
[self.button setAttributedTitle:normalTitle forState:UIControlStateNormal];
[self.button setAttributedTitle:highlightedTitle forState:UIControlStateHighlighted];
}

Update NSMutableAttributedString in another class

I have a UIButton class with a NSMutableAttributedString as the title (for the formatting).
I would like to now change the titleColor of the button text from my vc class because it has been'selected'.
I can do it fine as a normal button title. But as a NSMutableAttributedString - no dice.
Some questions/advice: As the custom class view is already a button - should my color update happen in that class - and not from the vc? Just tell it to update and bake the color in the custom class?
Do I expose the NSMutableAttributedString property for the button's title so that I can access from my VC and change the color? This way I could also pass in new text as well as a new color.
In my CircleButton m file
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setAlignment:NSTextAlignmentCenter];
[style setLineBreakMode:NSLineBreakByWordWrapping];
UIFont *font1 = [UIFont fontWithName:#"Futura" size:20.0f];
NSDictionary *dict1 = #{NSUnderlineStyleAttributeName:#(NSUnderlineStyleNone),
NSFontAttributeName:font1,
NSForegroundColorAttributeName:textClr,
NSParagraphStyleAttributeName:style};
attributedTText = [[NSAttributedString alloc] initWithString:btnTxt attributes:dict1];
[[button titleLabel] setNumberOfLines:0];
[[button titleLabel] setLineBreakMode:NSLineBreakByWordWrapping];
[button setAttributedTitle:attributedTText forState:UIControlStateNormal];
[button setTitleColor:textClr forState:UIControlStateNormal];

Title color of UIButton won't change on highlighted/selected but background color will

This has been a very odd process.
I have an IBOutletCollection of UIButtons. I loop through the collection and create them like this (the displayHourButtons is called from viewWillAppear):
- (void)displayHourButtons
{
// Counter
NSUInteger b = 0;
// Set attributes
UIFont *btnFont = [UIFont fontWithName:#"Metric-Semibold" size:13.0];
UIColor *btnTextColor = [UIColor colorWithRed:(147/255.0f) green:(147/255.0f) blue:(147/255.0f) alpha:1.0];
NSNumber *btnTracking = [NSNumber numberWithFloat:0.25];
NSMutableParagraphStyle *btnStyle = [[NSMutableParagraphStyle alloc] init];
[btnStyle setLineSpacing:2.0];
NSDictionary *btnAttrs = [NSDictionary dictionaryWithObjectsAndKeys:
btnFont, NSFontAttributeName,
btnTextColor, NSForegroundColorAttributeName,
btnTracking, NSKernAttributeName, nil];
// CREATE THE BUTTONS
for (UIButton *hourButton in hourButtons) {
// I'm using the attributed string for something else
// later in development that I haven't got to yet.
// I simplified the string for this example's sake.
NSString *btnTitleText = [NSString stringWithFormat:#"Button %lu", (unsigned long)b];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]
initWithString:btnTitleText
attributes:btnAttrs];
[attributedText addAttribute:NSParagraphStyleAttributeName
value:btnStyle
range:NSMakeRange(0, btnTitleText.length)];
CALayer *btnLayer = [hourButton layer];
[btnLayer setMasksToBounds:YES];
[btnLayer setCornerRadius:19.0f];
[hourButton setTag:b];
[hourButton setContentEdgeInsets:UIEdgeInsetsMake(5.0, 1.0, 0.0, 0.0)];
[hourButton setAttributedTitle:attributedText forState:UIControlStateNormal];
[hourButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
[hourButton setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
hourButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
[hourButton addTarget:self action:#selector(showHour:) forControlEvents:UIControlEventTouchUpInside];
b++;
}
}
When one of the buttons is clicked, per the action showHour: is called:
- (IBAction)showHour:(id)sender
{
[self.hourButtons enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIButton *button = (UIButton *)obj;
if (button != sender && button.enabled) {
// This is applied. I know because I tested it with redColor
[button setBackgroundColor:[UIColor clearColor]];
// Doesn't change, stays the gray set initially
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}
else {
// This is applied
[button setBackgroundColor:[UIColor colorWithRed:(169/255.0f) green:(234/255.0f) blue:(255/255.0f) alpha:1.0]];
// This is not
[button setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal | UIControlStateSelected | UIControlStateHighlighted)];
}
}];
// displayHour uses the tag to change labels, images, etc.
[self displayHour:(long int)[sender tag]];
}
I tried all sorts of crazy things to get the UIImage to be in a selected state, but nothing worked. This enumerateObjects deal is the only thing that has worked. That's why I say this has been an odd process. I guess buttons don't stay active indefinitely?
Anyways, MY QUESTION: Is there a certain reason why the title color isn't changing? Just the background? I suspect it has something to do with the background not being set initially, but I couldn't explain why.
Thanks!
UPDATED
Per #Timothy Moose's answer, below is the updated code.
- (IBAction)showHour:(id)sender
{
[self.hourButtons enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIButton *button = (UIButton *)obj;
// Grab the mutable string from the button and make a mutable copy
NSMutableAttributedString *attributedText = [[button attributedTitleForState:UIControlStateNormal] mutableCopy];
// Shared attribute styles
UIFont *btnFont = [UIFont fontWithName:#"Metric-Semibold" size:14.0];
NSNumber *btnTracking = [NSNumber numberWithFloat:0.25];
NSMutableParagraphStyle *btnStyle = [[NSMutableParagraphStyle alloc] init];
[btnStyle setLineSpacing:2.0];
// Since we can't set a color directly on a Attributed string we have
// to make a new attributed string.
if (button != sender && button.enabled) {
// Return to the default color
UIColor *btnTextColor = [UIColor colorWithRed:(147/255.0f) green:(147/255.0f) blue:(147/255.0f) alpha:1.0];
// Set up attributes
NSDictionary *btnAttrs = [NSDictionary dictionaryWithObjectsAndKeys:
btnFont, NSFontAttributeName,
btnTextColor, NSForegroundColorAttributeName,
btnTracking, NSKernAttributeName, nil];
// Reapply the default color (for the one button that was changed to white)
[attributedText setAttributes:btnAttrs
range:NSMakeRange(0, attributedText.length)];
// Add line-height
[attributedText addAttribute:NSParagraphStyleAttributeName
value:btnStyle
range:NSMakeRange(0, attributedText.length)];
// Reset default attributes
[button setBackgroundColor:[UIColor clearColor]];
[button setAttributedTitle:attributedText forState:UIControlStateNormal];
}
else {
// Our new white color for the active button
UIColor *btnTextColor = [UIColor whiteColor];
// Set up attributes
NSDictionary *btnAttrs = [NSDictionary dictionaryWithObjectsAndKeys:
btnFont, NSFontAttributeName,
btnTextColor, NSForegroundColorAttributeName,
btnTracking, NSKernAttributeName, nil];
// Apply our new white color
[attributedText setAttributes:btnAttrs
range:NSMakeRange(0, attributedText.length)];
// Add line-height
[attributedText addAttribute:NSParagraphStyleAttributeName
value:btnStyle
range:NSMakeRange(0, attributedText.length)];
// Add new attributes for active button
[button setBackgroundColor:[UIColor colorWithRed:(169/255.0f) green:(234/255.0f) blue:(255/255.0f) alpha:1.0]];
[button setAttributedTitle:attributedText forState:UIControlStateNormal];
}
}];
[self displayHour:(long int)[sender tag]];
}
setTitleColor doesn't have any effect when the title is an attributed string. Either use a plain NSString or call setAttributedTitle again after applying the desired color to the attributed string.
Also it is very important not to have the button on System style, just put it on custom...
This is for similar questions, not for this particular question.
I created a custom class MyButton extended from UIButton. Then added this inside the Identity Inspector:
After this, change the button type to Custom:
Then you can set attributes like textColor and UIFont for your UIButton for the different states:
Then I also created two methods inside MyButton class which I have to call inside my code when I want a UIButton to be displayed as highlighted:
- (void)changeColorAsUnselection{
[self setTitleColor:[UIColor colorFromHexString:acColorGreyDark]
forState:UIControlStateNormal &
UIControlStateSelected &
UIControlStateHighlighted];
}
- (void)changeColorAsSelection{
[self setTitleColor:[UIColor colorFromHexString:acColorYellow]
forState:UIControlStateNormal &
UIControlStateHighlighted &
UIControlStateSelected];
}
You have to set the titleColor for normal, highlight and selected UIControlState because there can be more than one state at a time according to the documentation of UIControlState.
If you don't create these methods, the UIButton will display selection or highlighting but they won't stay in the UIColor you setup inside the UIInterface Builder because they are just available for a short display of a selection, not for displaying selection itself.
In my case, I am using XCode 7.x.
I faced up with the similar problem. After using NSAttributedString
let underlineAttribute = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
let underlineAttributedString = NSAttributedString(string: "FILTER", attributes: underlineAttribute)
filterButton.setTitleColor(AppConfig.FOREGROUND, forState: .Normal)
filterButton.setAttributedTitle(underlineAttributedString, forState: .Normal)
the filterButton.setTitleColor(AppConfig.FOREGROUND, forState: .Normal) not get effected.
I change the Tint Color of the button in the Interface Builder (which is default as light blue). Now, it works for me now.
An alternative to the above answers is to apply the text colour using string attributes. You can set a different NSAttributedString for each control state, so this works to achieve the same effect - the button text will change colour on select/highlight.
Example:
// We're assuming attributedString already exists - this is your completed attributed string so far
// We're going to copy this string into two more NS(Mutable)AttributedString variables - one for the "normal" state and one for the "highlighted" state
NSMutableAttributedString *normalAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString];
// Set the desired foreground color (in this case it's for the "normal" state) for the length of the string
[normalAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,attributedString.length)];
// Rinse and repeat for the highlighted state
NSMutableAttributedString *highlightedAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString];
[highlightedAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,attributedString.length)];
// Finally, we'll set these as the attributedTitles for the relevant control states.
[myButton setAttributedTitle:normalAttributedString forState:UIControlStateNormal];
[myButton setAttributedTitle:highlightedAttributedString forState:UIControlStateSelected];
[myButton setAttributedTitle:highlightedAttributedString forState:UIControlStateHighlighted];
I noticed this immediately. Just a simple error probably :)
Change
UIColor *btnTextColor = [UIColor colorWithRed:(147/255.f)
green:(147/255.f)
blue:(147/255.f) alpha:1.0];
to
UIColor *btnTextColor = [UIColor colorWithRed:(147/255.0f)
green:(147/255.0f)
blue:(147/255.0f) alpha:1.0];
The reason it wasn't changing is probably because it wasn't recognizing the UIColor since you didn't have a full number in the division, since it was seeing (147/255.) instead of (147/255.0)

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

Resources