iphone - CALayer::hitTest 横向失败

标签 iphone ios calayer hittest

我的 View Controller 仅支持横向。我在主视图内添加了一个白色 View (whiteView - xib 中的 IBOutlet),并在whiteview 内添加了一个蓝色 CALayer(blueLayer - 类中的属性)。当我在此 View Controller 上运行 hitTest 时,它在应用程序窗口右侧的触摸上返回错误的结果,而在左侧一切正常。即使当前方向是横向,应用程序也好像以纵向模式运行。在纵向模式下一切正常。

下面是代码。在横向中,每次向右触摸都会返回“在主视图中触摸”。我需要做什么才能使其在横向模式下正常工作?

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.blueLayer = [[CALayer alloc] init];
    CGRect frame = self.whiteView.frame;
    self.blueLayer.frame = CGRectMake(20.0, 20.0, frame.size.width-40.0, frame.size.height - 40.0f);
    self.blueLayer.backgroundColor = [UIColor blueColor].CGColor;
    [self.whiteView.layer addSublayer:self.blueLayer];
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    CGPoint touchPoint = [[touches anyObject] locationInView:self.view];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"Touch in main view" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    CALayer *touchedLayer = [self.view.layer hitTest:touchPoint];

    if(touchedLayer == self.blueLayer){
        alertView.message = @"Touch in blue view";
    }
    else if (touchedLayer == self.whiteView.layer){
        alertView.message = @"Touch in white view";
    }
    else
        alertView.message = @"Touch in main view";

    [alertView show];
}

最佳答案

与方向无关。 根据苹果文档,“hitTest 返回该层的最远后代”。 按从上到下的顺序搜索 sibling 。触摸点位于接收器 super 层的坐标系中。 因此,在获取触摸点后立即添加此行。即

CGPoint touchPoint = [[touches anyObject] locationInView:self.view];
touchPoint = [self.view.layer convertPoint:touchPoint toLayer:self.view.layer.superlayer];
...........

关于iphone - CALayer::hitTest 横向失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18515730/

相关文章:

ios - 永远不会调用 CanMoveRowAtIndexPath

ios - 我应该为应用程序中的每个表创建一个 UITableViewCell 类吗?

ios - 防止 UICollectionViewCell 阴影转换到其他单元格上

ios - CALayer mask 会更新设备旋转

iphone - 如何使用条形按钮单击关闭弹出窗口

iphone - 用户创建表单,如 iOS 联系人创建

ios - 如何在下一个屏幕的自定义表格 View 单元格中显示多个选定的行

ios - 自动布局约束和 CALayer 问题

iphone - 如何在iphone中以编程方式获取 "General -> Date & Time -> Set Automatically"的值?

iphone - 从应用程序内关闭iPhone应用程序