gpt4 book ai didi

iOS - 访问子类的新属性

转载 作者:行者123 更新时间:2023-11-29 04:48:55 25 4
gpt4 key购买 nike

我是子类化的新手,但我想要一个 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]];

我不知道该怎么做。谢谢。

最佳答案

我在代码中做了同样的事情。我创建了 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];

关于iOS - 访问子类的新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9184998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com