前段时间我做了类似的事情。我只使用了触摸处理。可能是示例代码会有所帮助。
创建新的空项目。
添加到项目“coin.png”(PNG 图像 32x32,如下所示)。
在项目中创建名为 ViewController 的新文件作为 UIViewController 的子类,无需 xib。
在 AppDelegate.m 文件中删除所有并添加以下代码:
#import "AppDelegate.h"
#import "ViewController.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
_window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[_window makeKeyAndVisible];
ViewController *viewController = [ViewController new];
[_window setRootViewController:viewController];
return YES;
}
@end
在 ViewController.m 文件中删除所有并添加以下代码:
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic) int amount;
@property (nonatomic, strong) UILabel *count;
@property (nonatomic, strong) UIView *coinBox;
@end
@implementation ViewController
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if ([[touch view] isKindOfClass:[UIImageView class]])
{
[[touch view] setCenter:[touch locationInView:[[touch view] superview]]];
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if ([[touch view] isKindOfClass:[UIImageView class]])
{
[[touch view] setCenter:[touch locationInView:[[touch view] superview]]];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if ([[touch view] isKindOfClass:[UIImageView class]])
{
if(CGRectContainsRect(_coinBox.frame, [touch view].frame))
{
_amount += 5;
_count.text =[NSString stringWithFormat:@"Amount: %d",_amount];
[[touch view] setUserInteractionEnabled:NO];
}
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self createCoinBox];
[self createCoins];
}
- (void)createCoinBox
{
_coinBox = [[UIView alloc] initWithFrame:CGRectMake(120.0, 200.0, 80.0, 80.0)];
[_coinBox setBackgroundColor:[UIColor yellowColor]];
[[self view] addSubview:_coinBox];
_count = [[UILabel alloc] initWithFrame:CGRectMake(200.0, 200.0, 120.0, 32.0)];
[_count setBackgroundColor:[UIColor grayColor]];
[_count setText:@"Amount: 0"];
[[self view] addSubview:_count];
}
- (void)createCoins
{
for (int i = 0; i < 8; i++)
{
UIImageView *coin = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"coin"]];
CGRect coinFrame = CGRectMake(40.0 * i, 40.0, 32.0, 32.0);
[coin setFrame:coinFrame];
[coin setUserInteractionEnabled:YES];
[[self view] addSubview:coin];
}
}
@end
运行项目。并尝试在黄色盒子内外拖放一枚硬币