看到这章,突然觉得,这可能是可以做出很好玩应用的一个功能,下面是代码,很简单
<span style="font-size:18px;">
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSBundle *bundle = [NSBundle mainBundle];
self.imageTrashFull = [[UIImage alloc] initWithContentsOfFile:[bundle pathForResource:@"Blend Trash Full" ofType:@"png"]];
self.imageTrashEmpty = [[UIImage alloc] initWithContentsOfFile:[bundle pathForResource:@"Blend Trash Empty" ofType:@"png"]];
self.imageView.image = self.imageTrashFull;
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
UIDevice *device =[UIDevice currentDevice];
//开启接近传感器
device.proximityMonitoringEnabled = YES;
//设置通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(proximityDidChange:)
name:UIDeviceProximityStateDidChangeNotification
object:device];
}
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:YES];
UIDevice *device =[UIDevice currentDevice];
// 解除通知
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIDeviceProximityStateDidChangeNotification
object:nil];
device.proximityMonitoringEnabled = NO;
}
- (void)proximityDidChange:(NSNotificationCenter *)notification
{
if ([[UIDevice currentDevice] proximityState] == YES)
{
NSLog(@"用户接近");
self.imageView.image = self.imageTrashEmpty;
} else {
NSLog(@"用户离开");
self.imageView.image = self.imageTrashFull;
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
</span>
更多干货,请支持原作:http://item.jd.com/11436547.html