如何从视图控制器设置自定义UIView(圆圈)的填充颜色属性



我猜我对石英或CAShapeLayer操作还不够了解,但我想知道如何将填充颜色更改为自定义UIView。

以下是DotView的实现:

#define kCustomBlue     [UIColor colorWithRed:181.0/255 green:228.0/255 blue:226.0/255 alpha:1]
@implementation DotView

- (id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame])) {
self.backgroundColor = [UIColor clearColor];
self.opaque = YES;
}
return self;
}
- (id)initWithCoder:(NSCoder *)coder
{
if ((self = [super initWithCoder:coder])) {
self.backgroundColor = [UIColor clearColor];
self.opaque = YES;
}
return self;
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CAShapeLayer *circleLayer = [CAShapeLayer layer];
[circleLayer setPath:[[UIBezierPath bezierPathWithOvalInRect:rect] CGPath]];
circleLayer.fillColor = kCustomBlue.CGColor;
[self.layer addSublayer:circleLayer];
} 
@end

在我的故事板中放置一个DotView对象((nonatomic, weak)IBOutlet在我的ViewController界面中(后,我运行代码,一切都很好,很花花公子。 我的ViewController接口中的那个对象称为dot1

我想要一个属性@property (nonatomic, strong) UIColor* fillingColor;来设置视图的填充颜色。 如何正确实现?

这个想法是这样的:有一个点击手势识别器对象附加到dot1视图,每次我点击这个点时,颜色都会从蓝色变为黑色(然后从黑色变为蓝色(。

我正在使用XCode 9.3,并且有一部运行iOS 11.2的iPhone 7

谢谢,安东尼

将属性添加到 .h:

@interface DotView: UIView
// Add this to everything else you have
@property (nonatomic, strong) UIColor* fillingColor;
@end

然后在 .m 中,覆盖资源库:

- (void)setFillingColor:(UIColor *)color {
_fillingColor = color;
[self setNeedsDisplay];
}

然后在drawRect:中,使用填充颜色的fillingColor属性:

circleLayer.fillColor = self.fillingColor.CGColor;

请注意,您不希望每次调用drawRect:时都一遍又一遍地添加图层。您甚至不需要为此使用图层。只需填写UIBezierPath.

最新更新