2012-02-07 73 views
0

我是新来的子类,但我想要一个UILabel子类给标签中的任何文本具有3像素大纲。从this page,我用这个方法:iOS - 在子类上访问新属性

- (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

我在我的代码中做了同样的事情。我创建了具有属性的UILabel的子类,以设置边框颜色和边框宽度。

JKBorderedLabel.h

@interface JKBorderedLabel : UILabel 

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

@end 

JKBorderedLabel.m

​​

然后使用方法:

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

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

谢谢!我以为我尝试了类似的东西,但在其他类中,每当我键入“[myLabel”时,“setOutlineColor”选项都不会弹出。但是,我确实在Interface Builder中设置了该类,而不是通过代码对其进行初始化。这可能是一个问题,你觉得呢? – achiral 2012-02-08 02:19:55

+0

这是可能的。我没有尝试过通过IB使用它,但假设对象的类被设置为您的自定义类在身份检查器中,我会认为它应该工作。 – jonkroll 2012-02-08 02:34:36