archive-com.com » COM » T » TECHOTOPIA.COM

Total: 1018

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • A Swift iOS 8 Storyboard-based Collection View Tutorial - Techotopia
    is listing the code for the MyCollectionViewCell swift file then Ctrl click and drag from the Image View object to a position immediately beneath the class declaration line Release the line and in the resulting connection panel establish an outlet connection named imageView On completion of the connection select MyCollectionViewCell swift in the project navigator and verify that it reads as follows import UIKit class MyCollectionViewCell UICollectionViewCell IBOutlet weak var imageView UIImageView With the connection established the prototype cell implementation is complete Implementing the Data Model The data model for this example application is going to consist of a set of images each of which will be displayed in a cell within the collection view The first step in creating this model is to load the images into the project These images can be found in the carImagesSmall folder of the sample code archive which is downloadable from the following URL http www ebookfrenzy com web ios8 Once downloaded unzip the archive and drag and drop the 12 image files onto the Supporting Files section of the Xcode project navigator panel Next select the MyCollectionViewController swift file and declare an array into which will be stored the image file names Also change the reuseIdentifier constant to match the identifier assigned to the cell in Interface Builder import UIKit let reuseIdentifier MyCell class MyCollectionViewController UICollectionViewController var carImages String Finally edit the MyCollectionViewController swift file and modify the viewDidLoad method to initialize the array with the names of the car image files Also comment out or delete the following line so that it is no longer executed when the application runs As outlined in the previous chapter it is not necessary to register cell classes when using Storyboard prototypes self collectionView registerClass UICollectionViewCell self forCellWithReuseIdentifier reuseIdentifier The completed viewDidLoad method should read as follows override func viewDidLoad super viewDidLoad Uncomment the following line to preserve selection between presentations self clearsSelectionOnViewWillAppear false Do any additional setup after loading the view carImages chevy small jpg mini small jpg rover small jpg smart small jpg highlander small jpg venza small jpg volvo small jpg vw small jpg ford small jpg nissan small jpg honda small jpg jeep small jpg eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Implementing the Data Source As outlined in the chapter entitled An Overview of iOS 8 Collection View and Flow Layout a collection view needs a data source and a delegate in order to provide all the functionality it is capable of providing By default Xcode has designated the MyCollectionViewController class as both the delegate and data source for the UICollectionView in the user interface To verify this select the black background of the collection view controller in the storyboard to select the UICollectionView subclass instance and display the Connections Inspector select the far right item at the top of the Utilities panel or use the View Utilities Show Connection Inspector menu option Assuming that the connections have been made the Outlets section of the panel will be configured as shown in Figure 55 6 Figure 55 6 The next step is to declare which protocols the MyCollectionViewController class is going to implement Select the MyCollectionViewController swift file and modify it so that it reads as outlined in the following listing import UIKit let reuseIdentifier MyCell class MyCollectionViewController UICollectionViewController UICollectionViewDataSource UICollectionViewDelegate var carImages String A number of data source methods will now need to be modified to conform with the UICollectionViewDataSource protocol The first lets the collection view know how many sections are to be displayed For the purposes of this example there is only going to be one section so locate the numberOfSectionsInCollectionView method generated by Xcode and modify it to return a value of 1 override func numberOfSectionsInCollectionView collectionView UICollectionView Int return 1 The next method is called by the collection view to identify the number of items that are to be displayed in each section In this case the sole collection view section will be required to display a cell for each element in the carImages array Locate the template method and modify it as follows override func collectionView collectionView UICollectionView numberOfItemsInSection section Int Int return carImages count The cellForItemAtIndexPath method will be called by the collection view in order to obtain cells configured based on the indexPath value passed to the method This method will request a cell object from the reuse queue and then set the image on the Image View object which was configured in the cell prototype earlier in this chapter using the index path row as the index into the carImages array override func collectionView collectionView UICollectionView cellForItemAtIndexPath indexPath NSIndexPath UICollectionViewCell let cell collectionView dequeueReusableCellWithReuseIdentifier reuseIdentifier forIndexPath indexPath as MyCollectionViewCell Configure the cell let image UIImage named carImages indexPath row cell imageView image image return cell Testing the Application Compile and run the application either on a physical iPhone device or using the iOS Simulator Once loaded the collection view will appear as illustrated in Figure 55 7 Clearly each cell has been displayed at a fixed size causing the images to be compressed to fit into the containing cell In order to improve the visual experience some work is clearly still needed Figure 55 7 Setting Sizes for Cell Items When the prototype cell was designed it was set to a specific size Unless additional steps are taken each cell within the collection view will appear at that size This means that images are not displayed at their original size In actual fact all of the car images differ in size from each other What is needed is a way to set the size of each cell based on the size of the content it is required to display in this instance the dimensions of the corresponding image As outlined in the previous chapter if a method named

    Original URL path: http://www.techotopia.com/index.php/A_Swift_iOS_8_Storyboard-based_Collection_View_Tutorial (2016-02-13)
    Open archived version from archive


  • Subclassing and Extending the iOS 8 Collection View Flow Layout in Swift - Techotopia
    superclass let attributes super layoutAttributesForItemAtIndexPath indexPath Having ascertained what the attributes would normally be the method then calls a custom method named modifyLayoutAttributes and then returns the modified attributes to the collection view It will be the task of the modifyLayoutAttributes method which will be implemented later to apply the resize and movement effects to the attributes of the cell over which the pinch gesture is taking place Implementing the layoutAttributesForElementsInRect Method The layoutAttributesForElementsInRect method will need to perform a similar task to the previous method in terms of getting the attributes values for cells in the designated display region from the superclass calling the modifyLayoutAttributes method and returning the results to the collection view object override func layoutAttributesForElementsInRect rect CGRect AnyObject let allAttributesInRect super layoutAttributesForElementsInRect rect for cellAttributes in allAttributesInRect self modifyLayoutAttributes cellAttributes as UICollectionViewLayoutAttributes return allAttributesInRect Implementing the modifyLayoutAttributes Method By far the most interesting method to be implemented is the modifyLayoutAttributes method This is where the layout attributes for the cell the user is currently manipulating on the screen are modified This method should now be implemented as outlined in the following listing func modifyLayoutAttributes layoutattributes UICollectionViewLayoutAttributes if layoutattributes indexPath currentCellPath layoutattributes transform3D CATransform3DMakeScale currentCellScale currentCellScale 1 0 layoutattributes center currentCellCenter layoutattributes zIndex 1 In completing the example application a pinch gesture recognizer will be attached to the collection view object and configured to set the currentCellPath currentCellScale and currentCellCenter values of the layout object in real time as the user pinches and moves a cell As is evident from the above code use is made of these settings during the attribute modification process Since this method will be called for each cell in the collection it is important that the attribute modifications only be applied to the cell the user is currently moving and pinching This cell is stored in the currentCellPath property as updated by the gesture recognizer if layoutattributes indexPath currentCellPath If the cell matches that referenced by the currentCellPath property the attributes are transformed via a call to the CATransform3DMakeScale function of the QuartzCore Framework using the currentCellScale property value which is updated by the gesture recognizer during a pinching motion layoutattributes transform3D CATransform3DMakeScale currentCellScale currentCellScale 1 0 Finally the center location of the cell is set to the currentCellCenter property value and the zIndex property set to 1 so that the cell appears on top of overlapping collection view contents The implementation of a custom collection layout is now complete All that remains is to implement the gesture recognizer in the application code so that the flow layout knows which cell is being pinched and moved and by how much eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Adding the New Layout and Pinch Gesture Recognizer In order to detect pinch gestures a pinch gesture recognizer needs to be added

    Original URL path: http://www.techotopia.com/index.php/Subclassing_and_Extending_the_iOS_8_Collection_View_Flow_Layout_in_Swift (2016-02-13)
    Open archived version from archive

  • Drawing iOS 8 2D Graphics in Swift with Core Graphics - Techotopia
    the form of CGFloat variables An additional C structure named CGPoint is used to contain both the x and y coordinates to specify a point on the display Similarly the CGSize structure stores two CGFloat values designating the width and height of an element on the screen Further the position and dimension of a rectangle can be defined using the CGRect structure which contains a CGPoint the location and CGSize the dimension of a rectangular area Of key importance when working with points and dimensions is that these values do not correspond directly to screen pixels In other words there is not a one to one correlation between pixels and points Instead the underlying framework decides based on a scale factor where a point should appear and at what size relative to the resolution of the display on which the drawing is taking place This enables the same code to work on both higher and lower resolution screens for example an iPhone 3GS screen and an iPhone 6 retina display without the programmer having to worry about it For more precise drawing requirements iOS version 4 and later allows the scale factor for the current screen to be obtained from UIScreen UIView UIImage and CALayer classes allowing the correlation between pixels and points to be calculated for greater drawing precision For iOS 3 or older the scale factor is always returned as 1 0 The Graphics Context Almost without exception all Quartz API function calls require that the graphics context be passed as an argument Each view has its own context which is responsible for performing the requested drawing tasks and subsequently rendering those drawings onto the corresponding view The graphics context can be obtained with a call to the UIGraphicsGetCurrentContext function which returns a result of type CGContextRef let context UIGraphicsGetCurrentContext eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Working with Colors in Quartz 2D The Core Graphics CGColorRef data type is used to store colors when drawing with Quartz This data type holds information about the colorspace of the color RGBA CMYK or gray scale together with a set of component values that specify both the color and the transparency of that color For example the color red with no transparency would be defined with the RGBA components 1 0 0 0 0 0 1 0 A colorspace can be created via a Quartz API function call For example to create an RGB colorspace let colorSpace CGColorSpaceCreateDeviceRGB If the function fails to create a colorspace it will return a nil value Gray scale and CMYK color spaces may similarly be created using the CGColorSpaceCreateDeviceGray and CGColorSpaceCreateDeviceCMYK functions respectively Once the colorspace has been created the next task is to define the components The following declaration defines a set of RGBA components for a semi transparent blue

    Original URL path: http://www.techotopia.com/index.php/Drawing_iOS_8_2D_Graphics_in_Swift_with_Core_Graphics (2016-02-13)
    Open archived version from archive

  • Interface Builder Live Views and iOS 8 Embedded Frameworks - Techotopia
    Object Library panel onto the view controller canvas Resize the view stretching it in each dimension until the blue dotted line appears indicating the recommended margin Display the Auto Layout Pin menu and enable spacing to nearest neighbor constraints on all four sides of the view with the Constrain to margins option enabled as shown in Figure 58 1 before clicking on the Add 4 Constraints button Figure 58 1 Once the above steps are complete the layout should resemble that illustrated in Figure 58 2 below Figure 58 2 With the user interface designed the next step is to add a framework to the project Adding an Embedded Framework The framework to be added to the project will contain a UIView subclass containing some graphics drawing code Within Xcode select the File New Target menu option and in the template selection panel choose the Framework Library option listed under iOS in the left hand panel and Cocoa Touch Framework from the main panel Figure 58 3 Figure 58 3 Click on the Next button and on the subsequent screen enter MyDrawKit into the product name field before clicking on the Finish button Within the project navigator panel a new folder will have been added named MyDrawKit into which will be stored the files that make up the new framework Ctrl click on this entry and select the New File menu option In the template chooser panel select the Source entry listed under iOS in the left hand panel and Cocoa Touch Class from the main panel before clicking on Next On the next screen name the class MyDrawView and configure it as a subclass of UIView Click the Next button and save the new class file into the MyDrawKit subfolder of the project directory Select the Main storyboard file in the project navigator panel and click on the View object that was added in the previous section Display the Identity Inspector in the utilities panel and change the Class setting from UIView to MyDrawView Figure 58 4 eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Implementing the Drawing Code in the Framework The code to perform the graphics drawing on the View will reside in the MyDrawView swift file which is located in the Supporting Files subfolder of the MyDrawKit folder Locate this file in the project navigator panel and double click on it to load it into a separate editing window thereby allowing the Main storyboard file to remain visible in Interface Builder Remove the comment markers and from around the template drawRect method and implement the code for this method so that it reads as follows import UIKit import QuartzCore class MyDrawView UIView var startColor UIColor UIColor whiteColor var endColor UIColor UIColor blueColor var endRadius CGFloat 200 override func drawRect rect CGRect let context UIGraphicsGetCurrentContext

    Original URL path: http://www.techotopia.com/index.php/Interface_Builder_Live_Views_and_iOS_8_Embedded_Frameworks (2016-02-13)
    Open archived version from archive

  • An iOS 8 Swift Graphics Tutorial using Core Graphics and Core Image - Techotopia
    following graphics Figure 59 5 In order to draw a circle simply define a rectangle with equal length sides a square in other words Filling a Path with a Color A path may be filled with a color using a variety of Quartz 2D API functions Rectangular and elliptical paths may be filled using the CGContextFillRect and CGContextFillEllipse functions respectively Similarly a path may be filled using the CGContextFillPath function Prior to executing a fill operation the fill color must be specified using the CGContextSetFillColorWithColor function The following example defines a path and then fills it with the color red override func drawRect rect CGRect let context UIGraphicsGetCurrentContext CGContextMoveToPoint context 100 100 CGContextAddLineToPoint context 150 150 CGContextAddLineToPoint context 100 200 CGContextAddLineToPoint context 50 150 CGContextAddLineToPoint context 100 100 CGContextSetFillColorWithColor context UIColor redColor CGColor CGContextFillPath context The above code produces the following graphics on the device or simulator display when executed Figure 59 6 The following code draws a rectangle with a blue border and then once again fills the rectangular space with red override func drawRect rect CGRect let context UIGraphicsGetCurrentContext CGContextSetLineWidth context 4 0 CGContextSetStrokeColorWithColor context UIColor blueColor CGColor let rectangle CGRectMake 60 170 200 80 CGContextAddRect context rectangle CGContextStrokePath context CGContextSetFillColorWithColor context UIColor redColor CGColor CGContextFillRect context rectangle When added to the example application the resulting display should appear as follows Figure 59 7 Drawing an Arc An arc may be drawn by specifying two tangent points and a radius using the CGContextAddArcToPoint function for example override func drawRect rect CGRect let context UIGraphicsGetCurrentContext CGContextSetLineWidth context 4 0 CGContextSetStrokeColorWithColor context UIColor blueColor CGColor CGContextMoveToPoint context 100 100 CGContextAddArcToPoint context 100 200 300 200 100 CGContextStrokePath context The above code will result in the following graphics output Figure 59 8 Drawing a Cubic Bézier Curve A cubic Bézier curve may be drawn by moving to a start point and then passing two control points and an end point through to the CGContextAddCurveToPoint function override func drawRect rect CGRect let context UIGraphicsGetCurrentContext CGContextSetLineWidth context 4 0 CGContextSetStrokeColorWithColor context UIColor blueColor CGColor CGContextMoveToPoint context 10 10 CGContextAddCurveToPoint context 0 50 300 250 300 400 CGContextStrokePath context The above code will cause the curve illustrated in Figure 59 9 to be drawn when compiled and executed in our example application Figure 59 9 Drawing a Quadratic Bézier Curve A quadratic Bézier curve is drawn using the CGContextAddQuadCurveToPoint function providing a control and end point as arguments having first moved to the start point override func drawRect rect CGRect let context UIGraphicsGetCurrentContext CGContextSetLineWidth context 4 0 CGContextSetStrokeColorWithColor context UIColor blueColor CGColor CGContextMoveToPoint context 10 200 CGContextAddQuadCurveToPoint context 150 10 300 200 CGContextStrokePath context The above code when executed will display a curve that appears as illustrated in the following figure Figure 59 10 eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Dashed Line Drawing So far in this chapter we have performed all our drawing with a solid line Quartz also provides support for drawing dashed lines This is achieved via the Quartz CGContextSetLineDash function which takes as its arguments the following context The graphics context of the view on which the drawing is to take place phase A floating point value that specifies how far into the dash pattern the line starts lengths An array containing values for the lengths of the painted and unpainted sections of the line For example an array containing 5 and 6 would cycle through 5 painted unit spaces followed by 6 unpainted unit spaces count A count of the number of items in the lengths array For example a 2 6 4 2 lengths array applied to a curve drawing of line thickness 5 0 will appear as follows Figure 59 11 The corresponding drawRect code that drew the above line reads as follows override func drawRect rect CGRect let context UIGraphicsGetCurrentContext CGContextSetLineWidth context 20 0 CGContextSetStrokeColorWithColor context UIColor blueColor CGColor let dashArray CGFloat 2 6 4 2 CGContextSetLineDash context 3 dashArray 4 CGContextMoveToPoint context 10 200 CGContextAddQuadCurveToPoint context 150 10 300 200 CGContextStrokePath context Drawing Shadows In addition to drawing shapes Core Graphics can also be used to create shadow effects This is achieved using the CGContextSetShadow function passing through a graphics context offset values for the position of the shadow relative to the shape for which the shadow is being drawn and a value specifying the degree of blurring required for the shadow effect Colored shadows may similarly be created using the CGContextSetShadowWithColor function which takes an additional argument in the form of a CGColor object The following code for example draws an ellipse with a shadow override func drawRect rect CGRect let context UIGraphicsGetCurrentContext let myShadowOffset CGSizeMake 10 15 CGContextSaveGState context CGContextSetShadow context myShadowOffset 5 CGContextSetLineWidth context 4 0 CGContextSetStrokeColorWithColor context UIColor blueColor CGColor let rectangle CGRectMake 60 170 200 80 CGContextAddEllipseInRect context rectangle CGContextStrokePath context CGContextRestoreGState context When executed the above code will produce the effect illustrated in Figure 59 12 Figure 59 12 The color of the shadow could be changed for the sake of an example to red by calling CGContextSetShadowWithColor instead of CGContextSetShadow as follows CGContextSetShadowWithColor context myShadowOffset 5 UIColor redColor CGColor Drawing Gradients Gradients are implemented using the Core Graphics CGGradient class which provides support for linear radial and axial gradients Use of the CGGradient class essentially involves the specification of two or more colors together with a set of location values The location values are used to indicate the points at which the gradient should switch from one color to another as the gradient is drawn along an axis line where 0 0 represents the start of the axis and 1 0 the end point Assume for the purposes of an example that you wish to create a gradient that transitions through three different colors along the gradient axis with each color being given an

    Original URL path: http://www.techotopia.com/index.php/An_iOS_8_Swift_Graphics_Tutorial_using_Core_Graphics_and_Core_Image (2016-02-13)
    Open archived version from archive

  • Basic iOS 8 Swift Animation using Core Animation - Techotopia
    object named myView by a factor of 2 in both height and width myView transform CGAffineTransformMakeScale 2 2 Similarly the UIView object may be rotated using the CGAffineTransformMakeRotation function which takes as an argument the angle in radians by which the view is to be rotated The following code for example rotates a view by 90 degrees let angle CGFloat 90 M PI 180 myView transform CGAffineTransformMakeRotation angle The key point to keep in mind with transformations is that they become animated effects when performed within an animation block The transformations evolve over the duration of the animation and follow the specified animation curve in terms of timing eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Combining Transformations Two transformations may be combined to create a single transformation effect via a call to the CGAffineTransformConcat function This function takes as arguments the two transformation objects that are to be combined The result may then be assigned to the transform property of the UIView object to be transformed The following code fragment for example both scales and rotates a UIView object named myView let scaleTrans CGAffineTransformMakeScale 2 2 let angle CGFloat 90 M PI 180 let rotateTrans CGAffineTransformMakeRotation angle myView transform CGAffineTransformConcat scaleTrans rotateTrans Affine transformations offer an extremely powerful and flexible mechanism for creating animations and it is just not possible to do justice to these capabilities in a single chapter In order to learn more about affine transformations a good starting place is the Transforms chapter of Apple s Quartz 2D Programming Guide Creating the Animation Example Application The remainder of this chapter is dedicated to the creation of an iOS application intended to demonstrate the use of Core Animation The end result is a simple application on which a blue square appears When the user touches a location on the screen the box moves to that location Through the use of affine transformations the box will rotate 180 degrees as it moves to the new location whilst also changing in size Begin by launching Xcode and creating a new Single View Application project named Animate using Swift as the programming language and with the Universal device option selected Implementing the Variables For the purposes of this application we will need a UIView to represent the blue square and variables to contain the rotation angle and scale factor by which the square will be transformed These need to be declared in the ViewController swift file as follows import UIKit class ViewController UIViewController var scaleFactor CGFloat 2 var angle Double 180 var boxView UIView Drawing in the UIView Having declared the UIView reference we now need to initialize an instance object and draw a blue square located at a specific location on the screen We also need to add boxView as a subview of the application s main

    Original URL path: http://www.techotopia.com/index.php/Basic_iOS_8_Swift_Animation_using_Core_Animation (2016-02-13)
    Open archived version from archive

  • IOS 8 UIKit Dynamics – An Overview - Techotopia
    default vector can be changed if required at any time let vector CGVectorMake 0 0 0 5 gravity gravityDirection vector Finally the behavior needs to be added to the dynamic animator instance animator addBehavior gravity At any point during the application lifecycle dynamic items may be added to or removed from the behavior gravity addItem view3 gravity removeItem view Similarly the entire behavior may be removed from the dynamic animator animator removeBehavior gravity When gravity behavior is applied to a view and in the absence of opposing behaviors the view will immediately move in the direction of the specified gravity vector In fact as currently defined the view will fall out of the bounds of the reference view and disappear This can be prevented by setting up a collision behavior Configuring Collision Behavior UIKit Dynamics is all about making items move on the device display When an item moves there is a high chance it will collide either with another item or with the boundaries of the encapsulating reference view As previously discussed in the absence of any form of collision behavior a moving item can move out of the visible area of the reference view Such a configuration will also cause a moving item to simply pass over the top of any other items that happen to be in its path Collision behavior defined using the UICollisionBehavior class allows for such collisions to behave in ways more representative of the real world Collision behavior can be implemented between dynamic items such that certain items can collide with others or within boundaries allowing collisions to occur when a designated boundary is reached by an item Boundaries can be defined such that they correspond to the boundaries of the reference view or entirely new boundaries can be defined using lines and Bezier paths As with gravity behavior a collision is generally created and initialized with an array object containing the items to which the behavior is to be applied For example let collision UICollisionBehavior items view1 view2 animator addBehavior collision As configured view1 and view2 will now collide when coming into contact with each other What then happens will be decided by the physics engine depending on the elasticity of the items and the angle and speed of the collision In other words the engine will animate the items so that they behave as if they were physical objects subject to the laws of physics By default an item under the influence of a collision behavior will collide both with other items in the same collision behavior set and also with any boundaries set up To declare the reference view as a boundary simply set the translatesReferenceBoundsIntoBoundary property of the behavior instance to true collision translatesReferenceBoundsIntoBoundary true A boundary inset from the edges of the reference view may be defined using the setsTranslateReferenceBoundsIntoBoundaryWithInsets method passing through the required insets as an argument in the form of a UIEdgeInsets object The collisionMode property may be used to change default collision behavior by assigning one of the following constants UICollisionBehaviorMode Items Specifies that collisions only occur between items added to the collision behavior instance Boundary collisions are ignored UICollisionBehaviorMode Boundaries Configures the behavior to ignore item collisions recognizing only collisions with boundaries UICollisionBehaviorMode Everything Specifies that collisions occur between items added to the behavior and all boundaries This is the default behavior The following code for example enables collisions only for items collision collisionMode UICollisionBehaviorMode Items In the event that an application needs to react to a collision simply declare a class instance that conforms to the UICollisionBehaviorDelegate class by implementing the following methods and assign it as the delegate for the UICollisionBehavior object instance collisionBehavior beganContactForItem withBoundaryIdentifier atPoint collisionBehavior beganContactForItem withItem atPoint collisionBehavior endedContactForItem withBoundaryIdentifier collisionBehavior endedContactForItem withItem When implemented the application will be notified when collisions begin and end Note that in most cases the delegate methods will be passed information about the collision such as the location and the items or boundaries involved In addition aspects of the collision behavior such as friction and the elasticity of the colliding items such that they bounce on contact may be configured using the UIDynamicBehavior class This class will be covered in detail later in this chapter eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Configuring Attachment Behavior As the name suggests the UIAttachmentBehavior class allows dynamic items to be configured such that they behave as if attached These attachments can take the form of two items attached to each other or an item attached to an anchor point at specific coordinates within the reference view The attachment can take the form of an imaginary piece of cord that does not stretch or a spring attachment with configurable damping and frequency properties that control how bouncy the attached item is in response to motion By default the attachment point within the item itself is positioned at the center of the view This can however be changed to a different position causing the real world behavior outlined in Figure 61 2 to occur Figure 61 2 In general the physics engine will simulate animation to match what would typically happen in the real world As illustrated above the item will tilt when not attached in the center In the event that the anchor point moves the attached view will also move Depending on the motion the item will swing in a pendulum motion and assuming appropriate collision behavior configuration bounce off any boundaries it collides with as it swings As with all UIKit Dynamics behavior all the work to achieve this is performed for us by the physics engine The only effort required by the developer is to write a few lines of code to set up the behavior before adding it to the dynamic animator instance The following code for example

    Original URL path: http://www.techotopia.com/index.php/IOS_8_UIKit_Dynamics_%E2%80%93_An_Overview (2016-02-13)
    Open archived version from archive

  • A Swift iOS 8 UIKit Dynamics Tutorial - Techotopia
    150 20 60 60 redBoxView UIView frame frameRect redBoxView backgroundColor UIColor redColor self view addSubview blueBoxView self view addSubview redBoxView animator UIDynamicAnimator referenceView self view let gravity UIGravityBehavior items blueBoxView redBoxView let vector CGVectorMake 0 0 1 0 gravity gravityDirection vector animator addBehavior gravity Compile and run the application once again Note that after launching the gravity behavior causes the views to fall from the top of the reference view and out of view at the bottom of the device display In order to keep the views within the bounds of the reference view it is necessary to set up a collision behavior eBookFrenzy com Purchase the fully updated iOS 9 Swift 2 Xcode 7 edition of this book in eBook 12 99 or Print 39 99 format iOS 9 App Development Essentials Print and eBook ePub PDF Kindle edition contains 105 chapters Implementing Collision Behavior In terms of collision behavior the example requires that collisions occur both when the views impact each other and when making contact with the boundaries of the reference view With these requirements in mind the collision behavior needs to be implemented as follows override func viewDidLoad super viewDidLoad var frameRect CGRectMake 10 20 80 80 blueBoxView UIView frame frameRect blueBoxView backgroundColor UIColor blueColor frameRect CGRectMake 150 20 60 60 redBoxView UIView frame frameRect redBoxView backgroundColor UIColor redColor self view addSubview blueBoxView self view addSubview redBoxView animator UIDynamicAnimator referenceView self view let gravity UIGravityBehavior items blueBoxView redBoxView let vector CGVectorMake 0 0 1 0 gravity gravityDirection vector let collision UICollisionBehavior items blueBoxView redBoxView collision translatesReferenceBoundsIntoBoundary true animator addBehavior collision animator addBehavior gravity Running the application should now cause the views to stop at the bottom edge of the reference view and bounce slightly after impact The amount by which the views bounce in the event of a collision can be changed by creating a UIDynamicBehavior class instance and changing the elasticity property The following code for example changes the elasticity of the blue box view so that it bounces to a higher degree than the red box override func viewDidLoad super viewDidLoad let collision UICollisionBehavior items blueBoxView redBoxView collision translatesReferenceBoundsIntoBoundary true let behavior UIDynamicItemBehavior items blueBoxView redBoxView behavior elasticity 0 5 animator addBehavior behavior animator addBehavior collision animator addBehavior gravity Attaching a View to an Anchor Point So far in this tutorial we have added some behavior to the application but have not yet implemented any functionality that connects UIKit Dynamics to user interaction In this section however the example will be modified such that an attachment is created between the blue box view and the point of contact of a touch on the screen This anchor point will be continually updated as the user s touch moves across the screen thereby causing the blue box to follow the anchor point The first step in this process is to declare within the ViewController swift file some instance variables within which to store both the current location of the anchor point and a reference to a

    Original URL path: http://www.techotopia.com/index.php/A_Swift_iOS_8_UIKit_Dynamics_Tutorial (2016-02-13)
    Open archived version from archive



  •