如何在用户触摸屏幕时更改uiview颜色

问题描述:

我正在创建一个ipad应用程序,并且我有一个可以用红色填充和蓝色边框创建矩形的按钮。我想改变边框的颜色,当我触摸创建的矩形。我应该使用哪个声明?谢谢如何在用户触摸屏幕时更改uiview颜色

yourRect和borderColor是iVars。你必须写方法changeBorderColor来改变矩形被触摸时颜色变化的逻辑。

- (void) init 
{ 
    yourRect = CGRectMake(100,100, 200,200); 
    borderColor = [UIColor blueColor]; 

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)]; 
    singleTap.numberOfTapsRequired = 1;  
    [self addGestureRecognizer:singleTap:]; 
    [singleTap release]; 
} 

-(void)handleSingleTap:(UIGestureRecognizer *)gestureRecognizer 
{ 
    CGPoint tapLocation = [gestureRecognizer locationInView:shareView]; 

    if(CGRectContainsPoint(yourRect, tapLocation)) 
    { 
     borderColor = [self changeBorderColor]; //Change color 
    } 
} 

- (void)drawRect:(CGRect)rect; 
{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor); 
    CGContextFillRect(context, yourRect); 

    CGContextSetStrokeColorWithColor(context, borderColor.CGColor); 
    CGContextStrokeRect(context, yourRect); 
}