Gravity Sensor Code:
#import "ViewController.h" #import <CoreMotion/CoreMotion.h> @interface Viewcontroller ()//Create a Management object level @property ( Nonatomic, Strong) Cmmotionmanager *manager;//Create animated Object @property (Nonatomic, strong) Uidynamicanimator *dyanimat;// Gravity @property (nonatomic, strong) Uigravitybehavior *gravit;//collision @property (Nonatomic, strong) UICollisionBehavior * Collision; @end @implementation viewcontroller-(void) viewdidload {[Super viewdidload]; } #pragma mark-instantiated Object-(Cmmotionmanager *) Manager {if (_manager = = nil) {_manager = [[Cmmotionmanager alloc] I NIT]; _manager.devicemotionupdateinterval = 0.01; } return _manager;} -(Uidynamicanimator *) Dyanimat {if (_dyanimat = = nil) {_dyanimat = [[Uidynamicanimator alloc] Initwithreferen CeView:self.view]; } return _dyanimat;} -(Uigravitybehavior *) Gravit {if (_gravit = = nil) {_gravit = [[Uigravitybehavior alloc] init]; } return _gravit;} -(Uicollisionbehavior *) Collision {if (_collision = = nil){_collision = [[Uicollisionbehavior alloc] init]; _collision.translatesreferenceboundsintoboundary = YES; } return _collision;} #pragma mark-Animate the Object-(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (Uievent *) event {//up to 50 can be added if (Self.view.subviews.count >=) {NSLog (@ "Up to upper limit"); Return }//Get the point of the finger uitouch *touch = touches.anyobject; Cgpoint point = [Touch LocationInView:self.view]; Create and tangent fillets UIView *view = [[UIView alloc] Initwithframe:cgrectmake (0, 0, 20, 20)]; View.layer.cornerRadius = 10; View.layer.masksToBounds = YES; The point of the finger is the center of the view view.center = point; Random Color View.backgroundcolor = [Uicolor colorwithred:arc4random_uniform (255)/255.0 Green:arc4random_uniform (255)/ 255.0 Blue:arc4random_uniform (255)/255.0 alpha:1]; [Self.view Addsubview:view]; Add an object to the animation [Self.dyanimat AddBehavior:self.gravit]; [Self.dyanimat addBehavior:self.collision]; Add gravity effect to view [self.Gravit Additem:view]; Add a collision effect to the view [Self.collision Additem:view]; Start listening [Self.manager startDeviceMotionUpdatesToQueue:NSOperationQueue.mainQueue withhandler:^ (Cmdevicemotion * _ Nullable Motion, Nserror * _nullable error) {//set gravity direction self.gravit.gravityDirection = Cgvectormake (motion.g ravity.x,-MOTION.GRAVITY.Y); }]; Print the number of added controls NSLog (@ "%zd-%@", self.view.subviews.count, view); }-(void) didreceivememorywarning {[Super didreceivememorywarning]; Dispose of any resources the can be recreated.} @end
The following is the simulator, the normal situation is the real machine to test, because the level simulator is not able to measure.
iOS finishing (vii) Small applications-gravity sensing