Advertisements

Bordered UILabel

I was looking around on the internet for how to put a border around the text of a UILabel and found this post on stackoverflow that solved my problem. I decided to turn that solution into a UILabel subclass and share it here. Big thanks to kprevas for providing the answer!

SNBorderedLabel.h

#import <UIKit/UIKit.h>

@interface SNBorderdLabel : UILabel
{
   UIColor* _borderColor;
   int _borderSize;
}

@property (nonatomic, retain) UIColor* borderColor;
@property (nonatomic) int borderSize;

@end

SNBorderedLabel.m

#import "SNBorderdLabel.h"

@implementation SNBorderdLabel
@synthesize borderColor = _borderColor;
@synthesize borderSize = _borderSize;

- (id)initWithFrame:(CGRect)frame
{
   self = [super initWithFrame:frame];
   if (self) {
      _borderColor = [[UIColor whiteColor] retain];
      _borderSize = 1;

   }

   return self;
}

- (void)drawTextInRect:(CGRect)rect {

   CGSize shadowOffset = self.shadowOffset;
   UIColor *textColor = self.textColor;

   CGContextRef c = UIGraphicsGetCurrentContext();
   CGContextSetLineWidth(c, self.borderSize);

   CGContextSetLineJoin(c, kCGLineJoinRound);
   CGContextSetTextDrawingMode(c, kCGTextStroke);
   self.textColor = self.borderColor;
   [super drawTextInRect:rect];

   CGContextSetTextDrawingMode(c, kCGTextFill);
   self.textColor = textColor;
   self.shadowOffset = CGSizeMake(0, 0);
   [super drawTextInRect:rect];

   self.shadowOffset = shadowOffset;
}

@end

Here’s how to use it:

   SNBorderdLabel* textLabel = [[SNBorderdLabel alloc] init];
   textLabel.borderColor = [UIColor whiteColor];
   textLabel.borderSize = 2;

Hope that this helps you as much as it did me!

Advertisements