[Fall in love with Swift] Day8: Explaining Uikit gravity in Swift (i)

Source: Internet
Author: User
Tags uikit



Transferred from: http://www.itjhwd.com/swift-uikitzlx/



The term " gravity " seems to be very big in any industry field. So what is gravity in Swift? That is to put the lifeless things on our mobile screen into the gravitational force, so that they can show as if it really fell down due to gravity and the effect of natural bounce after touching an object.



To do this, we need two sharp knives:UIKit DynamicsandMotion Effects.


    • UIKit Dynamicsis aUIKitcomplete set of physics engines. It allows us to add some behavior to the interface elements in the program to achieve real-life actions such as gravity, springs, and so on. All you have to do is register the interface element in the engine and specify the good physical behavior, and the rest will be handed to the physics engine to complete.
    • Motion EffectsYou can create cool parallax effects, just like when you switch between the screen and the iphone. It is based on data calculation analysis provided by the Apple-provided gravity accelerator, which enables our interface elements to react accordingly to the tilt direction of the mobile device.


When the two are used together, we can make the program live, full of vitality.


Let's start with the attack of the cock wire


Let's pick some small examples to learnUIKit Dynamics.


Note: Due to personal coding habits, in the SWIFT code I still add;, in fact, can add no, according to our preferences.


Open Xcode6 New Project, selectiOS Application/Single View Application, name casually fetch, I named hereUIKitDynamicsDemo, we can seeSingle View Applicationthe directory structure:






Open theViewController.swiftfile andviewDidLoadadd the following code to the method:


Create a square view with the color set to blue-green, join the current view in Let square = UIView (Frame:cgrect (x:100, y:100, width:100, height:100)); square.backg Roundcolor = Uicolor.cyancolor (); Self.view.addSubview (square);


The above code adds a bluish-green square to our screenUIView. Running, we can see a dull blue-green square quietly on the screen:






If you're running with a real machine, you can shake your phone, tilt your phone, take a mobile phone, and see how that dumb block reacts and changes. The answer is to have a reaction and you'll be damned. Because the few lines of code we write can only make it stand motionless, how can it be moved? Then let us witness the moment of miracles!


Add Gravity behavior


ViewController.swiftadd two attributes to a file:


Uikit physics engine var animator:uidynamicanimator!;    Gravity behavior var gravity:uigravitybehavior!;


Note: The function of the exclamation mark in the code does not introduce too much here, please consult the official documentation yourself.



ThenviewDidLoadadd the following code to the method:


Instantiate the Uikit physics engine class for viewanimator = Uidynamicanimator (ReferenceView:self.view) for Viewcontroller;    Instantiate the gravity behavior class, currently only used for the square viewgravity = uigravitybehavior (items: [square]) just created;    Add gravity behavior to the Uikit physics engine class Animator.addbehavior (gravity);


Now compile and run, we can see this blue-green square began to do free fall, fell out of the bottom edge of the screen and then disappeared.






Let's take a look at the type of two properties we just added:


    • UIDynamicAnimatorBelongsUIKitto a class in the physics engine. Its role is to keep track of the various behavioral actions you add to the physics engine, such as the gravity behavior here, and provide the entire context. When instantiatedUIDynamicAnimator, its constructor needs to pass in areferenceViewparameter that tells it to track and make coordinatesView.
    • UIGravityBehavioris a model of simulated gravity that can be used for one or more elements. Its constructor needs to pass in an array whose contents are one or more elements that we want to have a gravitational expression on.


Most behaviors have some configuration properties, such as gravitational behavior, which can change the angle and rate of the property:


Instantiate the Uikit physics engine class, currently only used for the square Viewanimator = Uidynamicanimator (ReferenceView:self.view) just created;     Instantiate the gravity behavior class, currently only used for the square viewgravity = uigravitybehavior (items: [square]) just created;    Angle Gravigy.angle = 1.6;    Rate gravigy.magnitude = 0.1;    Add gravity behavior to the Uikit physics engine class Animator.addbehavior (gravity);


The above codeangleis the angle property of the gravity behavior,anglethe value of 0 o'clock, the square will move horizontally to the right, as the value increases, the square will change the angle clockwise. However, we want to simulate gravity in reality, so this property is not set and is not set by default when it is moved vertically downward. is the rate attribute of the gravitational behavior, the higher the value is, the faster the drop, andmagnitudewhen themagnitudevalue of the property is 0 o'clock, the block does not drop, so the minimum rate is 0.1.



Note: In the real world, the gravitational acceleration is aboutg = 9.80665m/s^29.8 meters per square second. According to Newton's second law, we can use0.5 * g * Time^2formulas to calculate the fall distance.
In the Uikit world of gravity, the formula for calculating the gravitational acceleration is the same, but the units are different. Not meters but pixels, that isg = 1000pixels/s^2, we can also use Newton's second law to calculate the distance our blocks fall within a unit of time. We just need to know that the greater the acceleration of gravity, the fastergthe fall, so the attributes in the above codemagnitudeare pretty much the meaning.


Can't let our squares fall a mile.


From the current code of health know that our block down to the bottom of the screen without any stop meaning, directly fell cliff down, see not see. We want our screen to look like a box, where the block is in the box and it stops when it drops to the bottom, then we need to set a boundary.



Add another attribute to theViewController.swiftfile:


Collision behavior Var collision:uicollisionbehavior!;


ThenviewDidLoadadd the following lines of code to the method:


Instantiate the collision behavior class, currently only used for the square viewcollision = uicollisionbehavior (items: [square]) just created;    Collision.translatesreferenceboundsintoboundary the boundary of the reference view as the collision boundary = true;    Add the collision behavior to the Uikit physics engine class Animator.addbehavior (collision);


The above code creates a boundary behavior that links one or more boundaries to the specified view and makes them interactive.



From the above code I can noticecollision.translatesReferenceBoundsIntoBoundary = true;this line of code, which means toUIDynamicAnimatorrefer to the boundary of the view as the trigger boundary of the collision behavior, so that we do not have to set the boundaries of the coordinates, very useful.



Then we compile and run to see, this time the small square fell to the bottom of the screen will have a collision effect, and will rebound a few, is not very realistic.





Advanced application of Collision behavior


Next we add a view in the screen, a rectangle and cross the middle of the screen,viewDidLoadadd the following code to the method:


Create a rectangular view with a color set to red, join the current view in let barrier = UIView (Frame:cgrect (x:0, y:300, width:140, height:20)); Barrier.backgro Undcolor = Uicolor.redcolor (); Self.view.addSubview (barrier);





But we find that the red barrier and the block do not have any interaction, and it is important to note that only views that are associated with the behavior will have interactive behavior. Let's take a look at the following diagram:






UIDynamicAnimatorThe engine references the view of the current screen, which gives the engine the entire coordinate system. Each behavior can be associated with multiple elements, each of which can be associated with more than one behavior, and the diagram above can clearly show the relationship between the various behaviors and elements in the current app. Because all behaviors are not associated with a rectangular view, theybarriercan be ignored.


Wake barrier


If we want tobarrierlive, we have to relate it to the collision behavior:


Instantiate the collision behavior class, currently acting on the square view and rectangle viewcollision = uicollisionbehavior (items: [Square,barrier]) just created;


Isbarrieradded to the array of collision behavior correlation elements. In this case, there will besquarebarriercollision behavior with the two view, so when they collide, they have a collision effect.



Compile and run, let's seebarrierwhat happens when we wake up:






Let's take a look at the diagram of the behavior and elements in the app now:






Take a look at the name I gave this red rectangular view:barrierYes, obstacles. But is it now a competent obstacle? Obviously not, when it collides with the blue-green square, it rotates and falls along the square.



Wait, whybarrierfall to the bottom of the screen is not likesquarethere will be a Tigger and then stop, but in slow rotation, feel the same gravity. Well, that's because we don't associate gravity withbarrierit, so it starts spinning like weightlessness.



This is obviously not the result I want, I want tosquarefall after the hitbarrier,barriermotionless, and thensquarehit seven meat and eight vegetarian. We're going to stop thatsquare!


Invisible boundary and collision effect


We first removebarrierthe collision effect, will:


Collision = Uicollisionbehavior (items: [Square,barrier]);


Switch


Collision = Uicollisionbehavior (items: [square]);


Then add another line of code below this line:


Collision = Uicollisionbehavior (items: [square]); Collision.addboundarywithidentifier ("Barrier", Forpath: Uibezierpath (Rect:barrier.frame));


This line of code means to add an invisible boundary to the collision effect, and its position and shape are thebarriersame. This creates an illusion that the redbarrierbecomes the boundary, and that the true boundary is hidden behind it. Compile and run, let's see what happens:






We see a collision behavior when a blue-green block hits a red barrier, and a blue-green block bounces off and flips down.



From the above we know that Swift's Uikit power engine is very powerful and can help us achieve amazing implementation behavior with a few lines of code. The next article will give you a detailed introduction to the story behind the collision behavior.



Reference Original: UIKit Dynamics Tutorial in Swift



[Fall in love with Swift] Day8: Explaining Uikit gravity in Swift (i)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.