iOS - 在子类上访问新属性

时间:2012-02-07 22:28:57

标签: ios properties subclass

我是子类化的新手,但是我想要一个UILabel子类给标签中的任何文本提供一个3像素的轮廓。从this page开始,我使用了这种方法:

- (void)drawTextInRect:(CGRect)rect 
{    
    CGSize shadowOffset = self.shadowOffset;   
    UIColor *textColor = self.textColor;    

    CGContextRef c = UIGraphicsGetCurrentContext();   

    CGContextSetLineWidth(c, 3);   
    CGContextSetLineJoin(c, kCGLineJoinRound);    
    CGContextSetTextDrawingMode(c, kCGTextStroke);   
    self.textColor = [UIColor whiteColor];   
    [super drawTextInRect:rect];    

    CGContextSetTextDrawingMode(c, kCGTextFill);   
    self.textColor = textColor;   

    self.shadowOffset = CGSizeMake(0, 0);   
    [super drawTextInRect:rect];    self.shadowOffset = shadowOffset;  
} 

这很好用,我可以更改颜色以显示我想要的文字和轮廓的任何颜色。

有人可以告诉我如何创建一个名为“outlineColor”的属性,这个属性允许我将这个子类设置为我想要的任何标签并更改大纲的颜色吗?

基本上,我希望能够将标签的类设置为“CustomLabelClass”,然后在其他类中我想说的话:

[myLabel setOutlineColor:[UIColor whiteColor]];

我不知道该如何解决这个问题。感谢。

1 个答案:

答案 0 :(得分:1)

我在代码中做了同样的事情。我创建了一个UILabel的子类,其属性用于设置边框颜色和边框宽度。

JKBorderedLabel.h

@interface JKBorderedLabel : UILabel

@property (nonatomic, retain) UIColor *borderColor;
@property (nonatomic) NSInteger borderWidth;

@end

JKBorderedLabel.m

#import "JKBorderedLabel.h"

@implementation JKBorderedLabel

@synthesize borderColor = _borderColor;
@synthesize borderWidth = _borderWidth;

- (void)drawTextInRect:(CGRect)rect {

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

    self.shadowOffset = CGSizeMake(0, 0);

    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(c, _borderWidth);
    CGContextSetLineJoin(c, kCGLineJoinRound);

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

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

    self.shadowOffset = shadowOffset;
}

- (void)sizeToFit
{
    [super sizeToFit];

    self.frame = CGRectMake(self.frame.origin.x,
                               self.frame.origin.y - _borderWidth,
                               self.frame.size.width + (_borderWidth * 2),
                               self.frame.size.height);
}

@end

然后使用:

JKBorderedLabel *myLabel = [[JKBorderedLabel alloc] init];

myLabel.text = @"Hello World";
myLabel.textColor = [UIColor whiteColor];
myLabel.borderColor = [UIColor blueColor];
myLabel.borderWidth = 4;
[myLabel sizeToFit];