我创建了一个自定义类AnimalView
,它是UIView
的子类,包含UILabel
和UIImageView
。
@interface AnimalView : UIView {
UILabel *nameLabel;
UIImageView *picture;
}
然后我在ViewController.view中添加了几个AnimalView
。在touchesBegan:withEvent:
方法中,我想检测被触摸的对象是否为AnimalView
。以下是viewController的代码:
@implementation AppViewController
- (void)viewDidLoad {
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:...
[self.view addSubview scrollview];
for (int i = 0; i<10; i++) {
AnimalView *newAnimal = [[AnimalView alloc] init];
// customization of newAnimal
[scrollview addSubview:newAnimal;
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
UIView *hitView = touch.view;
if ([hitView isKindOfClass:[AnimalView class]]) {
AnimalView *animal = (AnimalView *)hitView;
[animal doSomething];
}
}
然而,当我点击动物时没有任何反应。当我按hitView
检查NSLog(@"%@", [hitView class])
课程时,它始终显示UIView
而不是AnimalView
。将AnimalView添加到ViewController时,它是否更改为UIView?有什么方法可以取回自定义类的原始类吗?
答案 0 :(得分:3)
AnimalView可能没有启用用户交互,而忽略了触摸。尝试设置[myView setUserInteractionEnabled:YES];
答案 1 :(得分:2)
AnimalView中是否包含UIView子视图?他们可能是那些接触触摸事件的人。您可以通过在AnimalView的所有子视图中反转David描述的方法来禁用这些视图的用户交互。
答案 2 :(得分:2)
如果您在AnimalView中有子视图,则可以使用以下代码遍历superview层次结构以查看触摸是否由AnimalView的子视图处理:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
UIView *hitView = touch.view;
AnimalView *animal = nil;
while (hitView != nil) {
if ([hitView isKindOfClass:[AnimalView class]]) {
animal = (AnimalView *) hitView;
break;
}
hitView = [hitView superview];
}
if (animal) {
[animal doSomething];
}
}