我正在为tvOS编写一个游戏,需要使用触控板在屏幕上移动对象 - 而不是鼠标指针在Mac上移动。我遇到的问题是,在我的游戏中,UIViewController没有接收touchesBegan或touchesMoved。在网上看了一些关于touchesBegan没有在tvOS上工作的文章我写了一个小程序来测试这个理论
ViewController.h:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
CGPoint cursorLocation;
UIImageView* cursorImage;
}
@end
ViewController.m:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
cursorImage = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 92.0, 92.0)];
cursorImage.center = CGPointMake(CGRectGetMidX([UIScreen mainScreen].bounds), CGRectGetMidY([UIScreen mainScreen].bounds));
cursorImage.image = [UIImage imageNamed:@"Cursor"];
cursorImage.backgroundColor = [UIColor clearColor];
cursorImage.hidden = NO;
[self.view addSubview:cursorImage];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
cursorLocation = CGPointMake(-1, -1);
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
UITouch* touch = [touches anyObject];
CGPoint location = [touch locationInView:self.view];
if ((cursorLocation.x == -1) && (cursorLocation.y == -1)) {
cursorLocation = [touch locationInView:self.view];
} else {
float xDiff = location.x - cursorLocation.x;
float yDiff = location.y - cursorLocation.y;
CGRect rect = cursorImage.frame;
if ((rect.origin.x + xDiff >=0) && (rect.origin.x + xDiff <= self.view.frame.size.width)) {
rect.origin.x += xDiff;
}
if ((rect.origin.y + yDiff >=0) && (rect.origin.y + yDiff <= self.view.frame.size.height)) {
rect.origin.y += yDiff;
cursorImage.frame = rect;
cursorLocation = location;
}
}
}
@end
我的测试很精彩!我的问题是,什么可能阻止touchesBegan或touchesMoved被我的完整应用程序中的ViewController接收(其来源对于这个问题来说太长了)? Spitball离开 - 我没有想法,我欢迎任何你可能有的建议!
答案 0 :(得分:1)
您的示例代码没有任何手势识别器,但您的完整应用程序可能会这样做。某些手势可能导致touchesBegan:
永远不会被发送到响应者链。
您应该重试完整的应用,但尽可能多地移除手势识别器,您可能会发现touchesBegan:
方法开始被调用。
如果您确定问题实际上是一个手势,那么您可以通过在相关手势上将cancelsTouchesInView
设置为NO
或通过设置来获得与响应者链方法配合的手势delaysTouchesBegan
到NO
(虽然这应该是默认值)。
答案 1 :(得分:0)
如果启用tvOS焦点引擎,将不再调用触摸事件。只需在屏幕上放置UIButton
,或例如使用UITabBarController`,即可启用焦点引擎并禁用触摸事件。
如果您仍然需要触摸事件,请查看以下答案:UIButton blocking touchesBegan and touchesMoved