iphone - 无法获取 CALayer iOS 的正确位置

标签 iphone ios ios5 ios6

我正在 iOS 中使用 CALayer,在 myView 中添加了一个子图层,并尝试通过触摸开始获取触摸事件,但我收到的触摸事件不在我绘制图层的位置,如果有问题,请帮助我纠正它.

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   

我还包含了运行代码时收到的日志。

最佳答案

调用 -[CALayer hitTest] 时的 [self.view ConvertPoint:location fromView:nil] 表示“将 location 从窗口的坐标空间到self.view的坐标空间。

但是,location 已经在 View 的坐标空间中,因为您是通过将 self.view 传递给 -[UITouch locationInView: ]

关于iphone - 无法获取 CALayer iOS 的正确位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19355934/

相关文章:

ios - 在iPhone上以编程方式打开蓝牙

ios - CallKit 错误 com.apple.CallKit.error.requesttransaction 错误 2

ios - 适用于 ios 应用程序的 api 的 django csrf

iphone - 触摸移动拖动按钮

iphone - 将事件添加到 iPhone 应用程序的 iCal 中

html - 始终在 iPhone/Android 中显示滚动条

objective-c - cocoa 枚举

ios - 通过将 UIView 添加到 UIStackView 来动画化 UIView 过渡

ios - startMonitoringSignificantLocationChanges 和 startUpdatingLocation 如何相互影响?

iphone - NSMutableArray 和 removeobjectsatindex