我在 - LayoutView
中绘制了3个方块- (void)drawRect:(CGRect)rect
self.room1 = [UIBezierPath bezierPathWithRect:CGRectMake(81, 10, 60, 60)];
[self.normalColor setFill];
[self.room1 fill];
[[UIColor blackColor]setStroke];
self.room1.lineWidth = 1;
[self.room1 stroke];
然后我找到了正确的UIBezierPath
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"touch here");
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self];
if ([self.room1 containsPoint:touchPoint])
{
// do stuff
NSLog(@"room1 %@" , self.room1);
[[UIColor redColor] setFill];
[self.room1 fill];
[self setNeedsDisplay];
}
}
这是工作我触摸房间1和日志打印“room1”
但是如何更改房间1的颜色?
目前我收到错误
:CGContextSetFillColorWithColor:无效的上下文0x0。这是一个严重的错误。 ...
感谢您的帮助。
答案 0 :(得分:4)
实现此目的的一种方法是在touchesBegan方法中跟踪所选状态,并将所有fill和setFill语句保留在drawRect中。在下面的示例中,我在方块内每次触摸切换选定的状态,在蓝色和红色之间交替显示颜色。
@interface RDView ()
@property (strong,nonatomic) UIBezierPath *room1;
@property (strong,nonatomic) UIColor *normalColor;
@property (strong,nonatomic) UIColor *selectedColor;
@property (nonatomic) BOOL isSelected;
@end
@implementation RDView
-(id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
self.normalColor = [UIColor blueColor];
self.selectedColor = [UIColor redColor];
self.isSelected = NO;
}
return self;
}
- (void)drawRect:(CGRect)rect {
self.room1 = [UIBezierPath bezierPathWithRect:CGRectMake(81, 10, 60, 60)];
UIColor *colorToUse = (self.isSelected)? self.selectedColor : self.normalColor;
[colorToUse setFill];
[self.room1 fill];
[[UIColor blackColor]setStroke];
self.room1.lineWidth = 1;
[self.room1 stroke];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint touchPoint = [touches.anyObject locationInView:self];
if ([self.room1 containsPoint:touchPoint]){
self.isSelected = ! self.isSelected;
[self setNeedsDisplay];
}
}