(8/18) re-learn Standford_iOS7 development _ protocol, block, animation _ course notes, ios7 Layer Protocol

Source: Internet
Author: User

(8/18) re-learn Standford_iOS7 development _ protocol, block, animation _ course notes, ios7 Layer Protocol

Lesson 8:

1. Agreement

Another method of Security Processing id type is: id <MyProtocol> obj

A. Statement

// Protocols are generally stored in. in the H file or in the class. in the hfile @ protocol Foo <xy133, NSObject> // <> indicates which protocols need to be implemented. The root protocols of all protocols are generally NSObject-(void) someMethod; // The default method is required @ optional // optional method declaration-(void) methodWithArgument :( BOOL) argument; @ required @ property (readonly) int readonlyProperty; // only getter @ property NSString * readwriteProperty in the Protocol; // both getter and setter are in the protocol-(int) methodThatReturnsSomething; @ end

B. Implement the protocol in the class

# Import "Foo. h "@ interface MyClass: NSObject <Foo> has already existed // (do not have to declare Foo's methods again here, it's implicit that you implement it) @ end // or private implementation @ interface MyClass () <Foo> @ end @ implementation MyClass // @ required methods here! @ End

C. Purpose

① Delegate

② Data Source

// Method of blind communication between the UI and the controller @ property (nonatomic, weak) id <UISomeObjectDelegate> delegate; @ property (nonatomic, weak) id <UISomeObjectDataSource> dataSource;

③ Animation

2. Block (from API Documentation)

It is actually a block of code, similar to the function pointer in C language.

A. Statement

Int multiplier = 7; int (^ myBlock) (int) = ^ (int num) {return num * multiplier ;}; // int indicates the block return value. // ^ indicates that this is a code block. // myBlock indicates the block name. // int indicates the parameter type. // block is implemented on the right of the equal sign.

Block can use variables declared in the same range as other variables. Using block is similar to using C functions.

int multiplier = 7;int (^myBlock)(int) = ^(int num) {    return num * multiplier;}; printf("%d", myBlock(3));// prints "21"

B. Use block directly

Block can be omitted. block declaration can be used directly.

Char * myCharacters [3] = {"TomJohn", "George", "Charles Condomine"}; // use block directly as the parameter qsort_ B (myCharacters, 3, sizeof (char *), ^ (const void * l, const void * r) {char * left = * (char **) l; char * right = * (char **) r; return strncmp (left, right, 1) ;}); // myCharacters is now {"Charles Condomine", "George ", "TomJohn "}

C. Use block in Cocoa

NSArray * stringsArray = @ [@ "string 1", @ "String 21", @ "string 12", @ "String 11", @ "String 02"]; static compute comparisonOptions = inherit | NSNumericSearch | inherit | NSForcedOrderingSearch; NSLocale * currentLocale = [NSLocale currentLocale]; // The comparator is a code block NSComparator finderSortBlock = ^ (id string1, id string2) {nsange string1Range = NSMakeRange (0, [string1 length]); return [string1 compare: string2 options: comparisonOptions range: string1Range locale: currentLocale];}; NSArray * finderSortArray = [stringsArray sortedArrayUsingComparator: finderSortBlock]; NSLog (@ "finderSortArray: % @", finderSortArray);/* Output: finderSortArray ", "String 02", "String 11", "string 12", "String 21 ")*/

D. _ block Variable

First, let's look at a simple example.

// Directly use the int x = 123; void (^ printXAndY) (int) = ^ (int y) {printf ("% d \ n", x, y) ;}; printXAndY (456); // prints: 123 456 // The variable cannot be changed directly. The variable here is read-only int x = 123 for the block; void (^ printXAndY) (int) = ^ (int y) {x = x + y; // error printf ("% d \ n", x, y );};

Solution: Introduce the _ block Variable

__block int x = 123; //  x lives in block storage void (^printXAndY)(int) = ^(int y) {    x = x + y;    printf("%d %d\n", x, y);};printXAndY(456); // prints: 579 456// x is now 579

E. Use of various types of variables in the block

For common local variables, the value is saved when the block is declared, and changes to common local variables are invisible to the block.

// Pay attention to the block call time. extern NSInteger CounterGlobal; // block has the read and write permission on global variables. static NSInteger CounterStatic; // static variable {NSInteger localCounter = 42; // common local Variable _ block char localCharacter; // _ block local Variable void (^ aBlock) (void) = ^ (void) {++ CounterGlobal; ++ CounterStatic; counterGlobal = localCounter; // localCounter fixed at block creation localCharacter = 'a'; // sets localCharacter in enclosing scope}; ++ localCounter; // unseen by the block, invisible to the block, the block value is considered to be 42 localCharacter = 'B'; aBlock (); // execute the block // localCharacter now 'A '}

F. Use of objects in blocks

Dispatch_async (queue, ^ {/* block accesses the instance variable. instanceVariable is the instance variable of the class where the block is located. In this case, the instance variable is accessed directly. Therefore, you need to (self) keep */doSomethingWithObject (_ instanceVariable);}); id localVariable = _ instanceVariable; dispatch_async (queue, ^ {/* a local reference pointing to the instance variable is created, therefore, you must retain localVariable instead of self */doSomethingWithObject (localVariable );});

G. Use typedef to declare the block

typedef float (^MyBlockType)(float, float); MyBlockType myFirstBlock = // ... ;MyBlockType mySecondBlock = // ... ;

H. Memory Cycles

// The block references self, so a strong Pointer Points to self, and the block is defined in self, so self has a strong pointer to block [self. myBlocks addObject: ^ {[self doSomething] ;}];

Solution

_ Weak MyClass * weakSelf = self; // redeclare as weak reference [self. myBlocks addObject: ^ {[weakSelf doSomething];}];

I. Purpose

Enumeration, animation, sorting, Notification, Error handlers, Completion handlers (handle errors and completed events, which can be understood as Callback functions), multithreading, etc.

3. Animation)

A. animation types

Animating views: view animation, including movement, scaling, fade-in and fade-out, rotation, etc.

Animation of View Controller transitions: View Controller Animation, View switching, etc.

Core Animation: Core Animation framework

This lesson only covers view animation.

B. Three Ways to add animations to a view

① Set view attributes

Frame

Transform (translation, rotation and scale)

Alpha (opacity)

       The value is changed immediately, but the animation effect is delayed.

+ (Void) animateWithDuration :( NSTimeInterval) duration delay :( NSTimeInterval) delay options :( UIViewAnimationOptions) options animations :( void (^) (void) animations completion :( void (^) (BOOL finished) completion; // applicable to conventional animation settings // example [UIView animateWithDuration: 3.0 delay: 0.0 options: UIViewAnimationOptionBeginFromCurrentState animations: ^ {myView. alpha = 0.0;} completion: ^ (BOOL fin) {if (fin) [myView removeFromSuperview] ;}]; // The View fades out from the parent view within 3 seconds, after the animation is completed, remove yourself + (void) transitionWithView :( UIView *) view duration :( NSTimeInterval) duration options :( UIViewAnimationOptions) options animations :( void (^) (void )) animations completion :( void (^) (BOOL finished) completion; // applicable to transfer animation settings, such as card flip + (void) transitionFromView :( UIView *) fromView toView :( UIView *) toView duration :( NSTimeInterval) duration options :( UIViewAnimationOptions) options completion :( void (^) (BOOL finished) completion; // applicable to switching view animations

 

// UIViewAnimationOptions // set general animation attributes (you can select multiple attributes at the same time) UIViewAnimationOptionLayoutSubviews // The subview constraint is automatically updated when the parent view changes @ see: http://segmentfault.com/q/1010000002872390 UIViewAnimationOptionAllowUserInteraction // The animation responds to user events, such as touch and other UIViewAnimationOptionBeginFromCurrentState // starts the animation from the current state, for example, an animation is changing the property UIViewAnimationOptionRepeat // The animation UIViewAnimationOptionAutoreverse // executes the animation loop (the animation still returns to the initial position after it is run to the end point ), the premise is to set the animation to infinitely repeat UIViewAnimationOptionOverrideInheritedDuration // ignore the nested animation time settings else // ignore the nested animation speed settings UIViewAnimationOptionAllowAnimatedContent // re-paint the view during the animation process (note only applicable) UIViewAnimationOptionShowHideTransitionViews // hide the old view and display the new view directly when switching the view, instead of removing the old view from the parent view (only applicable to transition animation) UIViewAnimationOptionOverrideInheritedOptions // do not inherit the parent animation setting or animation type // animation Speed Control (you can select a setting from it) UIViewAnimationOptionCurveEaseInOut // The animation is slow first, then accelerate UIViewAnimationOptionCurveEaseIn // The animation slows down UIViewAnimationOptionCurveEaseOut // The animation gradually accelerates UIViewAnimationOptionCurveLinear // The animation is executed at a constant speed. The default value is // The transfer type (only applicable to, you can select one of them for setting. You do not need to set basic and key frame animations) UIViewAnimationOptionTransitionNone // No transition animation effect transition // flip from the left side effect transition // flip from the right side of the animation transition effect UIViewAnimationOptionTransitionCurlDown // animated transition effect for the forward flip // display the effect of the next new view after the old view is dissolved. UIViewAnimationOptionTransitionFlipFromTop // flip the effect from the top UIViewAnimationOptionTransitionFlipFromBottom // flip the effect from the bottom

② Dynamic Animator: Dynamic animation

Implementation steps: a. Create a UIDynamicAnimator

B. Add UIDynamicAnimator (gravity, collisions, etc .)

C. Add UIDynamicAnimator to UIDynamicItems (usually UIViews)

D. Automatic animation running

//Create a UIDynamicAnimatorUIDynamicAnimator *animator = [[UIDynamicAnimator alloc] initWithReferenceView:aView];//Create and add UIDynamicBehaviorsUIGravityBehavior *gravity = [[UIGravityBehavior alloc] init]; [animator addBehavior:gravity];UICollisionBehavior *collider = [[UICollisionBehavior alloc] init]; [animator addBehavior:collider];//Add UIDynamicItems to a UIDynamicBehaviorid <UIDynamicItem> item1 = ...; id <UIDynamicItem> item2 = ...; [gravity addItem:item1]; [collider addItem:item1]; [gravity addItem:item2];
// UIDynamicItem protocol @ protocol UIDynamicItem @ property (readonly) CGRect bounds; @ property (readwrite) CGPoint center; @ property (readwrite) CGAffineTransform transform; @ end // generally, the UIView can be used as an Item, and the UIDynamic protocol is implemented by nature. // The above attributes are generally changed by the animation. If you need to change them manually, you need to call-(void) updateItemUsingCurrentState :( id <UIDynamicItem>) item;

UIDynamicBehaviors

// UIGravityBehavior @ property CGFloat angle; // gravity direction, down by default @ property CGFloat magn.pdf; // 1.0 is 1000 points/s // UICollisionBehavior collision @ property UICollisionBehaviorMode collisionMode; // Items, Boundaries, Everything (default)-(void) Conflict :( NSString *) identifier forPath :( UIBezierPath *) path; // use UIBezierPath to customize the collision boundary @ property BOOL conflict; // reference view (Top view of dynamic animation) as collision boundary // UIAttachmentBehavior adsorption behavior-(instancetype) initWithItem :( id <UIDynamicItem>) item attachedToAnchor :( CGPoint) anchor; // use the point as the adsorption-(instancetype) initWithItem :( id <UIDynamicItem>) i1 attachedToItem :( id <UIDynamicItem>) i2; // use the dynamic item as the adsorption, adsorption of two power items-(instancetype) initWithItem :( id <UIDynamicItem>) item offsetFromCenter :( CGPoint) offset... // offset center adsorption @ property (readwrite) CGFloat length; // adsorption length @ property (readwrite) CGPoint anchorPoint; // adsorption point @ property (readwrite, nonatomic) CGFloat damping; // damping @ property (readwrite, nonatomic) CGFloat frequency when the anchor moves; // The frequency when the anchor moves // UISnapBehavior capturing behavior-(instancetype) initWithItem :( id <UIDynamicItem>) item snapToPoint :( CGPoint) point; @ property CGFloat damping ;. // damping of vibration when moving to the anchor point // uipus?havior driving behavior @ property uipus=haviormode mode; // Continuous or Instantaneous @ property CGVector pushDirection; @ property CGFloat magn.pdf/angle; // magnloud 1.0 moves a 100x100 view at 100 pts/s // UIDynamicItemBehavior dynamic behavior, applied to all Items @ property (readwrite, nonatomic) CGFloat elasticity; // elasticity, [0.1] @ property (readwrite, nonatomic) CGFloat friction; // friction, 0 indicates no friction @ property (readwrite, nonatomic) CGFloat density; // density, the default value is 1 @ property (readwrite, nonatomic) CGFloat resistance; // linear resistance coefficient 0--CGFLOAT_MAX @ property (readwrite, nonatomic) CGFloat angularResistance; // angle resistance coefficient 0--CGFLOAT_MAX @ property (readwrite, nonatomic) BOOL allowsRotation; // whether to allow rotation-(CGPoint) linearVelocityForItem :( id <UIDynamicItem>) item; // get Item speed-(CGFloat) angularVelocityForItem :( id <UIDynamicItem>) item; // get the Item Angular Velocity

Create a UIDynamicBehavior subclass to implement custom Behavior

-(Void) addChildBehavior :( UIDynamicBehavior *) behavior; // Add other behaviors to the custom row as @ property UIDynamicAnimator * dynamicAnimator; // obtain the animation of the current behavior-(void) willMoveToAnimator :( UIDynamicAnimator *) animator; // when the behavior is added to or removed (the parameter is nil), @ property (copy) void (^ action) (void) is called ); // This block is always executed when a behavior occurs. Pay attention to the efficiency of frequent calls.

4. demo

Dropit: https://github.com/NSLogMeng/Stanford_iOS7_Study/commit/515b76c7ed6e74a7e30108efe6d4c833f33a6e0c

 

Course video address: Netease Open Class: http://open.163.com/movie/2014/1/D/L/M9H7S9F1H_M9H80D0DL.html

Or use iTunes U to search for standford courses

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.