0

我是 iOS 的新手,我有一个问题:我有一个从UIImageViewsetUserInteractionEnabled扩展的对象,例如:

@interface CustomImageView : UIImageView

@property (retain, nonatomic) NSString *sNameImage;
@property (retain, nonatomic) NSString *sID;
@property (assign, nonatomic) float nPointX;
@property (assign, nonatomic) float nPointY;

-(void)setPoint:(NSString *)sPoint;

然后当我将它添加到UIView时:

for(int i = 0; i < self.arrCustomImageView.count; i++)
{
    CustomImageView *cuiv = [self.arrCustomImageView objectAtIndex:i];
    NSData *data = [self readDataFromFile:cuiv.sNameImage];
    if(data != nil && data.length > 0)
    {
        UIImage *image = [[UIImage alloc] initWithData:data];
        CGRect r = CGRectMake(cuiv.nPointX, cuiv.nPointY, image.size.width, image.size.height);
        [cuiv setUserInteractionEnabled:FALSE]; /*or NO i tried all*/
        [cuiv setImage:image];
        cuiv.frame = r;
        [self addSubview:cuiv];
        [image release];
        image = nil;
    }
}

然后在touchesBegan,我仍然在触摸它时捕获事件(触摸它时我仍然收到日志):|

然后源码 touchBegan 方法:

UITouch * touch = [touches anyObject];
for (UIView *aView in [self subviews])
{
    if (CGRectContainsPoint([aView frame], [touch locationInView:self]))
    {
        self.imvChoice = (CustomImageView *) aView;
        originalPoint = aView.frame.origin;
        offsetPoint = [touch locationInView:aView];
        nIndexChoice = [self.arrCustomImageView indexOfObject:aView];
        NSLog(@"log: %@ >> %@: id: %d", NSStringFromClass([self class]),NSStringFromSelector(_cmd), nIndexChoice);
        [self bringSubviewToFront:aView];
    }
}

我不认为这有问题,因为我尝试添加相同的 UIImageView,如下所示:

 for(int i = 0; i < [arrObject count]; i++)
{
    CustomObject *nsObj = [arrObject objectAtIndex:i];

    UIImageView *image1 = [self createUIImageView:[nsObj sName1] pointX:nsObj.pPoint1.x pointY:nsObj.pPoint1.y];
    image1.tag = i;
    [image1 setUserInteractionEnabled:FALSE];

    UIImageView *image2 = [self createUIImageView:[nsObj sName2] pointX:nsObj.pPoint2.x pointY:nsObj.pPoint2.y];
    image2.tag = i;
    [image2 setUserInteractionEnabled:TRUE];

    [self addSubview:image1];
    [self addSubview:image2];
    [image1 release];
    [image2 release];
}

它运行正常:| 当点击 image1 和 image2 时我无法捕捉事件。

所以我有错误?请给我解释一下!感谢大家的支持!

4

1 回答 1

3

接收整个视图控制器的touchesBegan触摸,而不仅仅是单个 uiview。如果您设置userInteractionEnabled为 false,则视图将不会接收任何视图特定事件,例如UITouchUpInside.

如果您想在touchesBegan用户单击“禁用”对象时检查您的方法,您必须获取用户触摸您的 ViewController 的坐标,例如像这样

UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPoint = [touch locationInView:self.view];

然后检查您的触摸点是否在您要检查的视图对象的矩形内

if (CGRectContainsPoint(cuiv, touchPoint){
    if (cuiv.userInteractionEnabled) {
     // your element is enabled, do something
    } else {
     // your element is disabled, do something else
    }
}
于 2014-05-13T09:24:19.670 回答