2013-10-14 50 views
0

我正在使用CALayer在iOS中在myView中添加了一个子图层,并尝试通过触摸来获取触摸事件,但是我正在获取触摸事件,而不是在绘制该图层的位置,请帮助我在纠正它时如果错误。未正确定位CALayer iOS

UIView *myView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
myView.backgroundColor = [UIColor whiteColor]; 

magicButton_ = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
magicButton_.frame = CGRectMake(10., 10., 300., 44.); 
[magicButton_ setTitle:@"Invoke Magic!" forState:UIControlStateNormal]; 
[magicButton_ addTarget:self action:@selector(toggleMoney:) forControlEvents:UIControlEventTouchUpInside]; 
[myView addSubview:magicButton_]; 

simpleLayer_ = [[CALayer alloc]init]; 


simpleLayer_.bounds = CGRectMake(0., 0., 150., 20.); 
simpleLayer_.position = CGPointMake((myView.center.x),(myView.center.y)); 
simpleLayer_.name = @"redlayer"; 
simpleLayer_.delegate = self; 
simpleLayer_.backgroundColor = [[UIColor redColor]CGColor]; 
[myView.layer addSublayer:simpleLayer_]; 
self.view = myView; 

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { 
    CGPoint location = [[touches anyObject] locationInView:self.view]; 
    CALayer *hitLayer = [self.view.layer hitTest:[self.view convertPoint:location    fromView:nil]]; 

    NSLog(@"Location %f %f",location.x,location.y); 
    [self displayInfo:hitLayer.name]; 
} 


-(void)displayInfo:(NSString *)nameOfLayer 
{ 
    NSLog(@"%@",nameOfLayer); 
} 

2013-10-14 13:13:37.374 MyLayerProj[1750:11303] (null) 
2013-10-14 13:13:38.468 MyLayerProj[1750:11303] Location 87.000000 269.000000 
2013-10-14 13:13:38.469 MyLayerProj[1750:11303] (null) 
2013-10-14 13:13:39.239 MyLayerProj[1750:11303] Location 112.000000 278.000000 
2013-10-14 13:13:39.240 MyLayerProj[1750:11303] redlayer 
2013-10-14 13:13:40.479 MyLayerProj[1750:11303] Location 119.000000 278.000000 

我还包括我在运行代码时得到的日志。

+0

从我看到有人使用CGLayer已经很长时间了。我希望有一些有趣的,老派的Core Graphics hackery,但不幸的是你在谈论CALayer(核心动画):( –

回答

1

在调用-[CALayer hitTest]意思是“从窗口的坐标空间变换locationself.view的坐标空间” [self.view convertPoint:location fromView:nil]

但是,location已经在视图的坐标空间中,因为您是通过从self.view-[UITouch locationInView:]获得的。

+0

那么在我的情况下获取位置的确切方式是什么 – user2007454

+0

只是不要使用额外的' - [UIView convertPoint:fromView:]',即只有'CALayer * hitLayer = [self.view.layer hitTest:location];' – hatfinch

+0

仍然在边界以外的点击记录 – user2007454