macOS 10.12.4 NSButton After adding CAGradientLayer, button title is not displayed - objective-c

The purpose of the following code is to achieve a gradient background color
In newer versions, it looks fine, but in macOS 10.12.4, the title of the button doesn't appear
- (void)setGradient:(NSArray<__kindof NSColor *> *)colorArr StartPoint:(CGPoint)startPoint EndPoint:(CGPoint)endPoint {
self.wantsLayer = YES;
CAGradientLayer *gradinentlayer = [CAGradientLayer layer];
NSMutableArray *array = [NSMutableArray array];
for (NSColor *color in colorArr) {
[array addObject:(id)color.CGColor];
}
gradinentlayer.colors = array;
gradinentlayer.startPoint = startPoint;
gradinentlayer.endPoint = endPoint;
gradinentlayer.frame = self.bounds;
[self.layer insertSublayer:gradinentlayer atIndex:0];
}
How do I make the title text appear, other than adding a subview?
Any help would be appreciated!
I've tried :
self.layer = gradinentlayer;
But this invalidates the layer's other Settings,This is not in line with expectations

Related

Render Title of MKPolygon

I'm trying to render MKPolygon using the following code:
NSMutableArray *overlays = [NSMutableArray array];
for (NSDictionary *state in states) {
NSArray *points = [state valueForKeyPath:#"point"];
NSInteger numberOfCoordinates = [points count];
CLLocationCoordinate2D *polygonPoints = malloc(numberOfCoordinates * sizeof(CLLocationCoordinate2D));
NSInteger index = 0;
for (NSDictionary *pointDict in points) {
polygonPoints[index] = CLLocationCoordinate2DMake([[pointDict valueForKeyPath:#"latitude"] floatValue], [[pointDict valueForKeyPath:#"longitude"] floatValue]);
index++;
}
MKPolygon *overlayPolygon = [MKPolygon polygonWithCoordinates:polygonPoints count:numberOfCoordinates];
overlayPolygon.title = [state valueForKey:#"name"];
[overlays addObject:overlayPolygon];
free(polygonPoints);
}
[self.stateMapView addOverlays:overlays];
I used the following code to provide stroke and fill colors:
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay NS_AVAILABLE(10_9, 7_0);
{
if ([overlay isKindOfClass:[MKPolygon class]])
{
MKPolygonRenderer *pv = [[MKPolygonRenderer alloc] initWithPolygon:overlay];
pv.fillColor = [UIColor redColor];
pv.strokeColor = [UIColor blackColor];
return pv;
}
return nil;
}
Do I need to do something to render the Title? I think I should enable a configuration or something but I'm new to MapView. Or I need to create a UILabel?
Overlays don't automatically show their titles like annotations can (in their callout actually) so there's nothing you "need to do" or any configuration that you can enable.
A simple workaround to show titles on overlays is, as you suggest, to create a UILabel.
However, this UILabel should be added to an annotation view that is positioned at each overlay's center.
A minor drawback (or maybe not) to this method is that the titles will not scale with the zoom of the map -- they'll stay the same size and can eventually collide and overlay with other titles (but you may be ok with this).
To implement this approach:
For each overlay, add an annotation (using addAnnotation: or addAnnotations:) and set the coordinate to the approximate center of the overlay and the title to the overlay's title.
Note that since MKPolygon implements both the MKOverlay and the MKAnnotation protocols, you don't necessarily need to create a separate annotation class or separate objects for each overlay. MKPolygon automatically sets its coordinate property to the approximate center of the polygon so you don't need to calculate anything. You can just add the overlay objects themselves as the annotations. That's how the example below does it.
Implement the mapView:viewForAnnotation: delegate method and create an MKAnnotationView with a UILabel in it that displays the title.
Example:
[self.stateMapView addOverlays:overlays];
//After adding the overlays as "overlays",
//also add them as "annotations"...
[self.stateMapView addAnnotations:overlays];
//Implement the viewForAnnotation delegate method...
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]])
{
//show default blue dot for user location...
return nil;
}
static NSString *reuseId = #"ann";
MKAnnotationView *av = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
if (av == nil)
{
av = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId];
av.canShowCallout = NO;
//add a UILabel in the view itself to show the title...
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
titleLabel.tag = 42;
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textColor = [UIColor blackColor];
titleLabel.font = [UIFont boldSystemFontOfSize:16];
titleLabel.textAlignment = NSTextAlignmentCenter;
titleLabel.minimumScaleFactor = 0.5;
[av addSubview:titleLabel];
av.frame = titleLabel.frame;
}
else
{
av.annotation = annotation;
}
//find the UILabel and set the title HERE
//so that it gets set whether we're re-using a view or not...
UILabel *titleLabel = (UILabel *)[av viewWithTag:42];
titleLabel.text = annotation.title;
return av;
}
The alternative approach is to create a custom overlay renderer and do all the drawing yourself (the polygon line, the stroke color, the fill color, and the text). See Draw text in circle overlay and Is there a way to add text using Paths Drawing for some ideas on how to implement that.

creating a line between two UIlabels using the long press gesture recognizer

i am developing a ER diagram editor, i have a bunch of draggable UILabels but all of them have the same name. i want to be able to create a line between two UIlabels when both are pressed together using the long press gesture recognizer. any help will be most appreciated
You can create your long press gesture on the superview shared by these two labels, e.g.:
UILongPressGestureRecognizer *twoTouchLongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self
action:#selector(handleLongPress:)];
twoTouchLongPress.numberOfTouchesRequired = 2;
[self.view addGestureRecognizer:twoTouchLongPress];
You can then write a gesture handler:
- (void)handleLongPress:(UILongPressGestureRecognizer *)gesture
{
if (gesture.state == UIGestureRecognizerStateBegan)
{
CGPoint location0 = [gesture locationOfTouch:0 inView:gesture.view];
CGPoint location1 = [gesture locationOfTouch:1 inView:gesture.view];
if ((CGRectContainsPoint(self.label0.frame, location0) && CGRectContainsPoint(self.label1.frame, location1)) ||
(CGRectContainsPoint(self.label1.frame, location0) && CGRectContainsPoint(self.label0.frame, location1)))
{
NSLog(#"success; draw your line");
}
else
{
NSLog(#"failure; don't draw your line");
}
}
}
In the updated comments, you suggest that you're creating a local UILabel variable, and then adding the resulting label to the view. That's fine, but you really want to maintain a backing model, that captures what you're doing in the view. For simplicity's sake, let me assume that you'll have array of these labels, e.g.:
#property (nonatomic, strong) NSMutableArray *labels;
Which you then initialize at some point (e.g. viewDidLoad):
self.labels = [[NSMutableArray alloc] init];
Then as you add labels to your view, add a reference to them in your array:
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(xVal, yVal, 200.0f, 60.0f)];
label.text = sentence;
label.layer.borderColor = [UIColor blueColor].CGColor;
label.layer.borderWidth = 0.0;
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont systemFontOfSize:19.0f];
[self.view addSubview:label];
[self.labels addObject:label];
Then, your gesture can do something like:
- (UILabel *)labelForLocation:(CGPoint)location
{
for (UILabel *label in self.labels)
{
if (CGRectContainsPoint(label.frame, location))
return label; // if found one, return that `UILabel`
}
return nil; // if not, return nil
}
- (void)handleLongPress:(UILongPressGestureRecognizer *)gesture
{
if (gesture.state == UIGestureRecognizerStateBegan)
{
CGPoint location0 = [gesture locationOfTouch:0 inView:gesture.view];
CGPoint location1 = [gesture locationOfTouch:1 inView:gesture.view];
UILabel *label0 = [self labelForLocation:location0];
UILabel *label1 = [self labelForLocation:location1];
if (label0 != nil && label1 != nil && label0 != label1)
{
NSLog(#"success; draw your line");
}
else
{
NSLog(#"failure; don't draw your line");
}
}
}
Frankly, I'd rather see this backed by a proper model, but that's a more complicated conversation beyond the scope of a simple Stack Overflow answer. But hopefully the above gives you an idea of what it might look like. (BTW, I just typed in the above without assistance of Xcode, so I'll apologize in advance for typos.)

iOS animations using CADisplayLink

I'm using animation and timing with CADisplayLink. When the ball touches a big stone it is removed immediately. How can I animate the removal of the stone (block) like exploding to small stones? Here's the code I currently have:
- (void)checkCollisionWithBlocks
{
for (BlockView *bv in blocks) {
if (CGRectIntersectsRect(bv.frame, ballRect)) {
ballVelocity.y = -ballVelocity.y;
[blocks removeObject:bv];
[bv removeFromSuperview];
break;
}
}
}
CADisplayLink is really a bit... much for what you're planning (it's for synchronizing screen drawing updates to a custom animation). Here's my solution: set some things on fire! While it's not necessarily an explosion, this will cause your block to belch some blue fire (you can change the color by modifying self.fireColor).
- (void)checkCollisionWithBlocks
{
for (BlockView *bv in blocks) {
if (CGRectIntersectsRect(bv.frame, ballRect)) {
ballVelocity.y = -ballVelocity.y;
[blocks removeObject:bv];
[bv burpFire]
[bv removeFromSuperview];
break;
}
}
}
#interface BlockView : UIView
#property (nonatomic, strong) CALayer *rootLayer;
#property (nonatomic, strong) CAEmitterLayer *fireEmitter;
#property (nonatomic, strong) CAEmitterLayer *smokeEmitter;
#property (nonatomic, strong) UIColor *fireColor;
#property (nonatomic, strong) UIColor *smokeColor;
-(void)burpFire;
#end
#implementation BlockView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.rootLayer = [CALayer layer];
//Set the root layer's background color to black
self.rootLayer.backgroundColor = [UIColor blackColor].CGColor;
//Create the fire emitter layer
self.fireEmitter = [CAEmitterLayer layer];
self.fireEmitter.emitterPosition = CGPointMake(0, CGRectGetMaxY(frame) + 50);
self.fireEmitter.emitterMode = kCAEmitterLayerOutline;
self.fireEmitter.emitterShape = kCAEmitterLayerLine;
self.fireEmitter.renderMode = kCAEmitterLayerAdditive;
self.fireEmitter.emitterSize = CGSizeMake(0, 0);
//Create the smoke emitter layer
self.smokeEmitter = [CAEmitterLayer layer];
self.smokeEmitter.emitterPosition = CGPointMake(0, CGRectGetMaxY(frame) + 50);
self.smokeEmitter.emitterMode = kCAEmitterLayerPoints;
//Create the fire emitter cell
CAEmitterCell* fire = [CAEmitterCell emitterCell];
fire.emissionLongitude = M_PI;
fire.birthRate = 0;
fire.velocity = -80;
fire.velocityRange = -30;
fire.emissionRange = -1.1;
fire.yAcceleration = -200;
fire.scaleSpeed = 0.3;
self.fireColor = [UIColor colorWithRed:0.425 green:0.779 blue:0.800 alpha:0.100];
fire.color = self.fireColor.CGColor;
fire.contents = (id)[self CGImageNamed:#"fire.png"];
//Name the cell so that it can be animated later using keypaths
[fire setName:#"fire"];
//Add the fire emitter cell to the fire emitter layer
self.fireEmitter.emitterCells = [NSArray arrayWithObject:fire] ;
//Create the smoke emitter cell
CAEmitterCell* smoke = [CAEmitterCell emitterCell];
smoke.birthRate = 11;
smoke.emissionLongitude = M_PI / 2;
smoke.lifetime = 0;
smoke.velocity = -40;
smoke.velocityRange = 20;
smoke.emissionRange = M_PI / 4;
smoke.spin = 1;
smoke.spinRange = 6;
smoke.yAcceleration = 160;
smoke.contents = (id) [self CGImageNamed:#"smoke.png"];
smoke.scale = 0.1;
smoke.alphaSpeed = -0.12;
smoke.scaleSpeed = 0.7;
//Name the cell so that it can be animated later using keypaths
[smoke setName:#"smoke"];
//Add the smoke emitter cell to the smoke emitter layer
self.smokeEmitter.emitterCells = [NSArray arrayWithObject:smoke];
//Add the two emitter layers to the root layer
[self.layer addSublayer:self.smokeEmitter];
[self.layer addSublayer:self.fireEmitter];
[self burpFire];
}
return self;
}
//Return a CGImageRef from the specified image file in the app's bundle
-(CGImageRef)CGImageNamed:(NSString*)name {
NSString *url = [[NSBundle mainBundle] pathForResource:name ofType:nil];
return [UIImage imageWithContentsOfFile:url].CGImage;
}
-(void)burpFire {
float gas = 80.0 / 100.0;
//Update the fire properties
[self.fireEmitter setValue:[NSNumber numberWithInt:(gas * 1000)] forKeyPath:#"emitterCells.fire.birthRate"];
[self.fireEmitter setValue:[NSNumber numberWithFloat:gas] forKeyPath:#"emitterCells.fire.lifetime"];
[self.fireEmitter setValue:[NSNumber numberWithFloat:(gas * 0.35)] forKeyPath:#"emitterCells.fire.lifetimeRange"];
self.fireEmitter.emitterSize = CGSizeMake(100 * gas, 0);
//Update the smoke properites
[self.smokeEmitter setValue:[NSNumber numberWithInt:gas * 4] forKeyPath:#"emitterCells.smoke.lifetime"];
self.smokeColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:gas * 0.3];
[self.smokeEmitter setValue:(__bridge id)self.smokeColor.CGColor forKeyPath:#"emitterCells.smoke.color"];
[self setNeedsDisplay];
[self performSelector:#selector(burpFinished) withObject:nil afterDelay:1.5];
}
-(void)burpFinished {
float gas = 0.0 / 100.0;
//Update the fire properties
[self.fireEmitter setValue:[NSNumber numberWithInt:(gas * 1000)] forKeyPath:#"emitterCells.fire.birthRate"];
[self.fireEmitter setValue:[NSNumber numberWithFloat:gas] forKeyPath:#"emitterCells.fire.lifetime"];
[self.fireEmitter setValue:[NSNumber numberWithFloat:(gas * 0.35)] forKeyPath:#"emitterCells.fire.lifetimeRange"];
self.fireEmitter.emitterSize = CGSizeMake(100 * gas, 0);
//Update the smoke properites
[self.smokeEmitter setValue:[NSNumber numberWithInt:gas * 4] forKeyPath:#"emitterCells.smoke.lifetime"];
self.smokeColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:gas * 0.3];
[self.smokeEmitter setValue:(__bridge id)self.smokeColor.CGColor forKeyPath:#"emitterCells.smoke.color"];
}
The CAEmitterLayers last for quite a while, so if you want the fire to shut off a little faster, play around with the timing of the stop selector. If you want smaller or larger fire, or fireballs that stick around longer, play around with the properties in the init method, either way you're gonna get a cool effect.
All colors must be strong references to UIColor, else Core Animation will freak out and throw a C++ temper tantrum in your debugger... not pleasant.

Scroll to xib (pagecontrol)

i had a small question, i'm using this code to scroll from color to color:
NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil];
you can scroll from color to color, but is there a way to scroll to another xib file?
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil];
for (int i = 0; i < colors.count; i++) {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
UIView *subview = [[UIView alloc] initWithFrame:frame];
subview.backgroundColor = [colors objectAtIndex:i];
[self.scrollView addSubview:subview];
[subview release];
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * colors.count, self.scrollView.frame.size.height);
}
This tutorial will help you out: http://www.iosdevnotes.com/2011/03/uiscrollview-paging/
(i think that you've use this tutorial)
but on the last line of the tutorial:
Update: In the comments, some people have asked about placing buttons
inside the scroll view, and also about setting up the scroll view
using Interface Builder. I’ve added some code that includes buttons
here, and a version using Interface Builder here.
So here is the link to move to xib files: https://github.com/cwalcott/UIScrollView-Paging/tree/buttons-ib
Good luck,
Nathan
Instead of preparing UIView's and adding them to a scrollview, you could indeed use [[NSBundle mainBundle] loadNibNamed... to load several nib (which are compiled xib) and add them to a scrollview, and then scroll them up and down, or back and forth.

Objective C - Help with changing background color when UIButton is pressed

I am new to programing and any help is appreciated. I am trying to change the background color of a button once it has been pressed. I have tried setBackgroundColor without success. I am not sure that it is compatible with UIButton. Is there any way to programatically accomplish such a task? All thoughts and suggestions are appreciated.
I woudl suggest creating a simple image that contains the background color you want and setting that via the existing methods in the UIButton. (check Wrights Answer for the doc link).
UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
NSString* fileLocation = [[NSBundle mainBundle] pathForResource:#"buttonBG" ofType:#"png"];
UIImage* bgImage = [UIImage imageWithContentsOfFile:fileLocation];
if (bgImage != nil) { // check if the image was actually set
[button setBackgroundImage:bgImage forState:UIControlStateHighlighted];
} else {
NSLog(#"Error trying to read the background image");
}
That should do the trick. There might be an even better way to create the necessary image on the fly, but that's stuff I'm not firm in.
[edit: a bit more verbose code ]
Assuming you have an unadorned custom button with a title of "On" for the normal state:
- (IBAction) toggleButtonState {
if ([toggleButton titleForState:UIControlStateNormal] == #"On") {
[toggleButton setTitle: #"Off" forState:UIControlStateNormal];
[toggleButton setBackgroundColor:[UIColor redColor]];
}
else {
[toggleButton setTitle: #"On" forState:UIControlStateNormal];
[toggleButton setBackgroundColor:[UIColor greenColor]];
}
}
All the other buttons have an image placed in front of the view, so at most you'll see the corners change if the image doesn't completely fill the space.
I'd also suggest using an image, but for learning purposes, this will work.
Ive just been having the same issue and ended up using a UIButton subclass to tackle the issue. I used gradients simply because it looked a bit better if you have no need for them you can simply remove them. I have explained the process I used and included the full code at the bottom of the post.
Firstly add properties for the layers.I created two layers one for the base gradient and one for a gloss to add a little bit of style.
#interface gradientButton()
#property (nonatomic, strong) CAGradientLayer* gradientLayer;
#property (nonatomic, strong) CAGradientLayer* glossyLayer;
#end
Then either in -(void)awakeFromNib or in -(id)initWithFrame:(CGRect)frame
,depending on if you will load from storyboard or code respectively, configure the gradients and add the layers, round your corners off and customize the font highlight color.
-(void)awakeFromNib
{
_gradientLayer = [[CAGradientLayer alloc] init];
_gradientLayer.bounds = self.bounds;
_gradientLayer.position = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
[self.layer insertSublayer:_gradientLayer atIndex:0];
self.layer.cornerRadius = 5.0f;
self.layer.masksToBounds = YES;
self.layer.borderWidth = 1.0f;
_glossyLayer = [[CAGradientLayer alloc] init];
_glossyLayer.bounds = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height/2);
_glossyLayer.position = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/4);
[self.layer addSublayer:_glossyLayer];
[self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self setTitleColor:[UIColor yellowColor] forState:UIControlStateHighlighted];
}
Next, override - (void)drawRect:(CGRect)rect to apply your layers and define your colors.
#define GRADIENT_TOP [UIColor colorWithRed:38.0/255.0 green:78.0/255.0 blue:54.0/255.0 alpha:1]
#define GRADIENT_BOTTOM [UIColor colorWithRed:44.0/255.0 green:71.0/255.0 blue:56.0/255.0 alpha:1]
#define GLOSS_TOP [UIColor colorWithRed:0.70f green:0.70f blue:0.70f alpha:0.95f]
#define GLOSS_BOTTOM [UIColor colorWithRed:0.70f green:0.70f blue:0.70f alpha:0.35f]
#define GRADIENT_SELECTED_TOP [UIColor colorWithRed:138.0/255.0 green:178.0/255.0 blue:154.0/255.0 alpha:1]
#define GRADIENT_SELECTED_BOTTOM [UIColor colorWithRed:114.0/255.0 green:171.0/255.0 blue:156.0/255.0 alpha:1]
- (void)drawRect:(CGRect)rect
{
[_gradientLayer setColors:#[(id)[GRADIENT_TOP CGColor],(id)[GRADIENT_BOTTOM CGColor]]];
[_glossyLayer setColors:#[(id)[GLOSS_TOP CGColor], (id)[GLOSS_BOTTOM CGColor]]];
[super drawRect:rect];
}
Finally, and the bit we've all been waiting for, override -(void)setHighlighted:(BOOL)highlighted{
so we can apply the highlight effect were looking for.
-(void)setHighlighted:(BOOL)highlighted{
[super setHighlighted:highlighted];
if(highlighted)
[_gradientLayer setColors:#[(id)[GRADIENT_SELECTED_TOP CGColor],(id)[GRADIENT_SELECTED_BOTTOM CGColor]]];
else
[_gradientLayer setColors:#[(id)[GRADIENT_TOP CGColor],(id)[GRADIENT_BOTTOM CGColor]]];
}
There we have it, now just drag out a UIButton modify the class and your all good. Heres the full Implementation so you can copy it straight out. http://pastebin.com/nUVeujyp
Check out the UIButton Class Reference.
Regular UIButtons do not have the backgroundColor option.
My suggestion would to use the UISegmentedControl, which has the tinColor option.
I have created a subclass which get background color and creates an UIImage for each state.
For me it's more useful a subclass instead a category, so that's up to you.
#implementation ROCRoundColorButton
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
UIColor *darkColor;
darkColor = [self darkColorFromBackgroundColor];
[self setBackgroundImage:[self imageWithColor:self.backgroundColor withSize:self.frame.size] forState:UIControlStateNormal];
[self setBackgroundImage:[self imageWithColor:darkColor withSize:self.frame.size] forState:UIControlStateSelected];
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
UIColor *darkColor;
darkColor = [self darkColorFromBackgroundColor];
[self setBackgroundImage:[self imageWithColor:self.backgroundColor withSize:self.frame.size] forState:UIControlStateNormal];
[self setBackgroundImage:[self imageWithColor:darkColor withSize:self.frame.size] forState:UIControlStateSelected];
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
#pragma mark -
#pragma mark Private methods
- (UIColor *)darkColorFromBackgroundColor
{
const float* components = CGColorGetComponents( self.backgroundColor.CGColor );
CGFloat red = components[0];
CGFloat green = components[1];
CGFloat blue = components[2];
CGFloat alpha = components[3];
if (red > 0) {
red -= 0.1;
}
if (green > 0) {
green -= 0.1;
}
if (blue > 0) {
blue -= 0.1;
}
UIColor *darkColor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
return darkColor;
}
- (UIImage *)imageWithColor:(UIColor *)color withSize:(CGSize)size
{
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
//CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height));
UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, size.width, size.height) cornerRadius:5];
[roundedRect fillWithBlendMode: kCGBlendModeNormal alpha:1.0f];
[color setFill];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
In fact, you can use it in the storyboard, changing the class and setting de background color in the view.