Подкласс UIView не реагирует на прикосновения - PullRequest
1 голос
/ 07 июня 2011

Я делаю проект для iPad, в котором класс с именем «Car» (это отдельный файл от контроллера представления) должен перетаскиваться по основному виду.

Я установил класс какЯ видел в примере Apple, и я могу просмотреть свое изображение, когда я запускаю приложение, но мой класс не реагирует на событие касаний, и я не могу решить проблему.

Вотмой код класса: Car.h

#import <UIKit/UIKit.h>


@interface Car : UIView {

    UIImageView *firstPieceView;
    CGPoint startTouchPosition;

}

-(void)animateFirstTouchAtPoint:(CGPoint)touchPoint forView:(UIImageView *)theView;
-(void)animateView:(UIView *)theView toPosition:(CGPoint) thePosition;
-(void)dispatchFirstTouchAtPoint:(CGPoint)touchPoint forEvent:(UIEvent *)event;
-(void)dispatchTouchEvent:(UIView *)theView toPosition:(CGPoint)position;
-(void)dispatchTouchEndEvent:(UIView *)theView toPosition:(CGPoint)position;

@property (nonatomic, retain) IBOutlet UIImageView *firstPieceView;

@end

и это мой другой код класса: Car.m

#import "Car.h"

    @implementation Car

    @synthesize firstPieceView;

    #define GROW_ANIMATION_DURATION_SECONDS 0.15    // Determines how fast a piece size grows when it is moved.
    #define SHRINK_ANIMATION_DURATION_SECONDS 0.15  // Determines how fast a piece size shrinks when a piece stops moving.


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

        // Enumerate through all the touch objects.
        NSUInteger touchCount = 0;
        for (UITouch *touch in touches) {
            // Send to the dispatch method, which will make sure the appropriate subview is acted upon
            [self dispatchFirstTouchAtPoint:[touch locationInView:self] forEvent:nil];
            touchCount++;  
        }   
    }

    // Checks to see which view, or views, the point is in and then calls a method to perform the opening animation,
    // which  makes the piece slightly larger, as if it is being picked up by the user.
    -(void)dispatchFirstTouchAtPoint:(CGPoint)touchPoint forEvent:(UIEvent *)event
    {
        if (CGRectContainsPoint([firstPieceView frame], touchPoint)) {
            [self animateFirstTouchAtPoint:touchPoint forView:firstPieceView];
        }   
    }

    // Handles the continuation of a touch.
    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
    {  

        NSUInteger touchCount = 0;
        // Enumerates through all touch objects
        for (UITouch *touch in touches) {
            // Send to the dispatch method, which will make sure the appropriate subview is acted upon
            [self dispatchTouchEvent:[touch view] toPosition:[touch locationInView:self]];
            touchCount++;
        }
    }

    // Checks to see which view, or views, the point is in and then sets the center of each moved view to the new postion.
    // If views are directly on top of each other, they move together.
    -(void)dispatchTouchEvent:(UIView *)theView toPosition:(CGPoint)position
    {
        // Check to see which view, or views,  the point is in and then move to that position.
        if (CGRectContainsPoint([firstPieceView frame], position)) {
            firstPieceView.center = position;
        } 
    }

    // Handles the end of a touch event.
    -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    {
        // Enumerates through all touch object
        for (UITouch *touch in touches) {
            // Sends to the dispatch method, which will make sure the appropriate subview is acted upon
            [self dispatchTouchEndEvent:[touch view] toPosition:[touch locationInView:self]];
        }
    }

    // Checks to see which view, or views,  the point is in and then calls a method to perform the closing animation,
    // which is to return the piece to its original size, as if it is being put down by the user.
    -(void)dispatchTouchEndEvent:(UIView *)theView toPosition:(CGPoint)position
    {   
        // Check to see which view, or views,  the point is in and then animate to that position.
        if (CGRectContainsPoint([firstPieceView frame], position)) {
            [self animateView:firstPieceView toPosition: position];
        } 
    }

    -(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
    {
        // Enumerates through all touch object
        for (UITouch *touch in touches) {
            // Sends to the dispatch method, which will make sure the appropriate subview is acted upon
            [self dispatchTouchEndEvent:[touch view] toPosition:[touch locationInView:self]];
        }
    }

    #pragma mark -
    #pragma mark === Animating subviews ===
    #pragma mark

    // Scales up a view slightly which makes the piece slightly larger, as if it is being picked up by the user.
    -(void)animateFirstTouchAtPoint:(CGPoint)touchPoint forView:(UIImageView *)theView 
    {
        // Pulse the view by scaling up, then move the view to under the finger.
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:GROW_ANIMATION_DURATION_SECONDS];
        theView.transform = CGAffineTransformMakeScale(1.2, 1.2);
        [UIView commitAnimations];
    }

    // Scales down the view and moves it to the new position. 
    -(void)animateView:(UIView *)theView toPosition:(CGPoint)thePosition
    {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:SHRINK_ANIMATION_DURATION_SECONDS];
        // Set the center to the final postion
        theView.center = thePosition;
        // Set the transform back to the identity, thus undoing the previous scaling effect.
        theView.transform = CGAffineTransformIdentity;
        [UIView commitAnimations];  
    }



    - (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {

            UIImage *img = [ UIImage imageNamed: @"CyanSquare.png" ];
            firstPieceView = [[UIImageView alloc] initWithImage: img];
            //[img release];
            [super addSubview:firstPieceView];
            [firstPieceView release];

        }
        return self;
    }

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    - (void)drawRect:(CGRect)rect
    {
        // Drawing code
    }
    */

    - (void)dealloc
    {
        [firstPieceView release];
        [super dealloc];
    }

    @end

А вот мой код для контроллера представления: (ParkingviewController.h)

#import <UIKit/UIKit.h>
#import "Car.h"


@interface ParkingViewController : UIViewController {

}

@end

и последнее, но не менее важное: ParkingViewController.m

#import "ParkingViewController.h"

@implementation ParkingViewController

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{   


    Car *car1 = [[Car alloc] init];
    [self.view addSubview:car1];
    [car1 release];
    [super viewDidLoad];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
}

@end

Пожалуйста, прости меня, если я разместил весь код, но я хочу быть ясным во всех аспектах моегопроект, так что любой может иметь ясность всей ситуации.

1 Ответ

1 голос
/ 07 июня 2011

Вам нужно установить рамку для Car объекта, который вы создаете для касаний, которые будут обработаны.Вы можете видеть изображение, так как для свойства clipsToBounds представления установлено значение NO по умолчанию.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...