I am trying to set an image as the background of a custom UIButton. I was able to set a background image for the \"rounded rect\" UIButton in interface builder, but now the
I'd just like to add to the answers provided by nanshi and Jonathan.
In order to access the border
and cornerRadius
properties of the layer you will first need to import the QuartzCore framework.
#import <QuartzCore/QuartzCore.h>
Otherwise you will not be able to access the properties.
You can set the border properties on the CALayer by accessing the layer property of the button.
First, add Quartz
#import <QuartzCore/QuartzCore.h>
Set properties:
[[myButton layer] setBorderWidth:2.0f];
[[myButton layer] setBorderColor:[UIColor greenColor].CGColor];
You could also "User Defined Runtime Attributes" in IB to set rounded corners like done in image below.
http://i.stack.imgur.com/uBkuB.png
When you set a background image in a button, the button outlines go away. Include them in your image, if you need different sizes look at the UIImage
stretchableImageWithLeftCapWidth:topCapHeight:
method.
Check out the cornerRadius
, borderWidth
and borderColor
properties of CALayer
. These properties are new as of iPhone OS 3.0.
You probably want to subclass UIButton
and then set these properties in the constructor. Your button has a layer property you can access to set these border properties.
Here's an example:
- (id)initWithFrame:(CGRect)frame {
if(self = [super initWithFrame:frame]) {
[self.layer setBorderWidth:1.0];
[self.layer setCornerRadius:5.0];
[self.layer setBorderColor:[[UIColor colorWithWhite:0.3 alpha:0.7] CGColor]];
}
return self;
}
#import <QuartzCore/QuartzCore.h> // don't forget to add this in your file
CALayer * layer = [yourUIButton layer];
[layer setMasksToBounds:YES];
[layer setCornerRadius:0.0]; //when radius is 0, the border is a rectangle
[layer setBorderWidth:1.0];
[layer setBorderColor:[[UIColor grayColor] CGColor]];
i know this is an old question, but still i would like to post my answer here. since i was looking for answer but got this resolved myself in an easy way.