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".
  • An iPad iOS 6 Gesture Recognition Tutorial - Techotopia
    has been detected Select the MainStoryboard storyboard file and drag a Label object from the Object Library panel to the center of the view Once positioned stretch the label horizontally to the outer edges of the view until the blue dotted lines representing the recommended margins appear and then modify the label properties to center the label text Select the label object in the view canvas display the Assistant Editor panel and verify that the editor is displaying the contents of the RecognizerViewController h file Ctrl click on the same label object and drag to a position just below the interface line in the Assistant Editor Release the line and in the resulting connection dialog establish an outlet connection named statusLabel Next the non visual gesture recognizer objects need to be added to the design Scroll down the list of objects in the Object Library panel until the Tap Gesture Recognizer object comes into view Drag and drop the object onto the View in the design area if the object is dropped outside the view the connection between the recognizer and the view on which the gestures are going to be performed will not be established Repeat these steps to add Pinch Rotation Swipe and Long Press Gesture Recognizer objects to the design Note that document outline panel has updated to reflect the presence of the gesture recognizer objects as illustrated in Figure 50 1 Figure 50 1 Within the document outline panel select the Tap Gesture Recognizer instance and display the Attributes Inspector View Utilities Show Attributes Inspector Within the attributes panel change the Taps value to 2 so that only double taps are detected Similarly select the Long Press Recognizer object and change the Press Duration attribute to 3 seconds Having added and configured the gesture recognizers the next step is to connect each recognizer to its corresponding action method Display the Assistant Editor and verify that it is displaying the content of RecognizerViewController h Ctrl click on the Tap Gesture Recognizer object in the document outline panel and drag the line to the area immediately beneath the newly created outlet in the Assistant Editor panel Release the line and within the resulting connection dialog establish an Action method configured to call a method named tapDetected with the id value set to UITapGestureRecognizer as illustrated in Figure 50 2 Figure 50 2 Repeat these steps to establish action connections for the pinch rotation swipe and long press gesture recognizers to methods named pinchDetected rotationDetected swipeDetected and longPressDetected respectively taking care to select the corresponding id value for each action On completion of the above steps the RecognizerViewController h should read as follows import UIKit UIKit h interface RecognizerViewController UIViewController property strong nonatomic IBOutlet UILabel statusLabel IBAction tapDetected UITapGestureRecognizer sender IBAction rotationDetected UIRotationGestureRecognizer sender IBAction pinchDetected UIPinchGestureRecognizer sender IBAction swipeDetected UISwipeGestureRecognizer sender IBAction longPressDetected UILongPressGestureRecognizer sender end Implementing the Action Methods Having configured the gesture recognizers the next step is to write the action methods that will be called

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


  • An Overview of iPad iOS 6 Collection View and Flow Layout - Techotopia
    fitting into the currently visible display region are visible The flow layout class supports both horizontal and vertical scrolling configurable via the scrollDirection property In addition properties such as the spacing between lines of cells in the grid and cells in a row may be configured together with default sizes for cells and supplementary views unless overridden via methods implemented in the delegate object The UICollectionViewLayoutAttributes Class Each item in a collection view be it a cell or a supplementary view has associated with it a set of attributes The UICollectionViewLayoutAttributes class serves as an object into which these attributes can be stored and transferred between objects A Flow Layout object will for example be asked by the collection view object to return the attributes for a cell at a given index in a collection view via a call to the layoutAttributesForItemAtIndexPath method This method in turn returns those attributes encapsulated in a UICollectionViewLayoutAttributes object Similarly such object instances can be used to apply new attributes to a collection view element The attributes stored by the UICollectionViewLayoutAttributes class are as follows keeping in mind that this class may be subclassed and extended to allow the storage of other values alpha the transparency of the item center the location of the center of the item frame the CGRect frame in which the item is displayed hidden whether or not the item is currently visible indexPath the index path location of the item in the collection view representedElementCategory The type of item for which the attributes apply i e for a cell supplementary or decoration view size the size of the item transform3D the current transform of the item Attribute can be used to perform tasks such as rotating or scaling the item zIndex controls the position of the item in the z axis in other words whether or not it is on top of or below other overlapping items The UICollectionViewDataSource Protocol The UICollectionViewDataSource protocol needs to be implemented by the class responsible for supplying the collection view with the pre configured cells and supplementary views to be displayed to the user This basically consists of a number of methods that define information such how many items of data are to be displayed how the data is divided into different sections and most importantly supplies the collection view with the cell objects to be displayed Mandatory methods in the protocol are as follows collectionView numberOfItemsInSection Returns the number of items to be displayed in the specified section of the collection view collectionView cellForItemAtIndexPath This method is called by the collection view when it is ready to display a cell at the specified index path location in the collection view It is required to return a cell object configured appropriately for the referenced index Optional methods in the protocol are as follows numberOfSectionsInCollectionView Indicates to the collection view the number of sections into which the collection view is to be divided collectionView viewForSupplementaryElementOfKind atIndexPath Called by the collection view to request a

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

  • An iPad iOS 6 Storyboard-based Collection View Tutorial - Techotopia
    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 h file and declare an array into which will be stored the image file names import UIKit UIKit h interface MyCollectionViewController UICollectionViewController property strong nonatomic NSMutableArray carImages end Finally edit the MyCollectionViewController m file and modify the viewDidLoad method to initialize the array with the names of the car image files void viewDidLoad super viewDidLoad carImages chevy volt jpg bmw mini jpg range rover jpg smart fortwo jpg toyota highlander jpg toyota venza jpg volvo s60 jpg vw cc jpg ford explorer jpg nissan gtr jpg honda jpg jeep overland jpg mutableCopy Note that we are using Modern Objective C syntax to initialize the array As outlined in the chapter entitled The Basics of Modern Objective C this approach returns a non mutable array by default Later in the chapter we will be implementing code to remove items from the array so need to call the mutableCopy method of the array to make sure we can modify the array later Implementing the Data Source As outlined in the chapter entitled An Overview of iOS 6 Collection Views 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 in 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 52 5 Figure 52 5 The next step is to declare which protocols the MyCollectionViewController class is going to implement Since the class will also need to work with the MyCollectionViewCell class now is also a good opportunity to import the header file for this class Select the MyCollectionViewController h file and modify it so that it reads as outlined in the following listing import UIKit UIKit h import MyCollectionViewCell h interface MyCollectionViewController UICollectionViewController UICollectionViewDataSource UICollectionViewDelegate property strong nonatomic NSMutableArray carImages end A number of data source methods will now be implemented 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 select the MyCollectionViewController m file and implement the numberOfSectionsInCollectionView method to return a value of 1 pragma mark pragma mark UICollectionViewDataSource NSInteger numberOfSectionsInCollectionView UICollectionView collectionView 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 NSInteger collectionView UICollectionView collectionView numberOfItemsInSection NSInteger section 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 UICollectionViewCell collectionView UICollectionView collectionView cellForItemAtIndexPath NSIndexPath indexPath MyCollectionViewCell myCell collectionView dequeueReusableCellWithReuseIdentifier MyCell forIndexPath indexPath UIImage image int row indexPath row image UIImage imageNamed carImages row myCell imageView image image return myCell Testing the Application Compile and run the application either on a physical iPad device or using the iOS Simulator Once loaded the collection view will appear as illustrated in Figure 52 6 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 52 6 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 sizeForItemAtIndexPath is implemented in the UICollectionViewFlowLayoutDelegate protocol class which by default is the same class as the UICollectionViewDelegate delegate it will be called for each cell to request size information Clearly by implementing this method it will be possible to have each image displayed at its own size Remaining in MyCollectionViewController m implement this method to identify the size of the current image and return the result to the collection view pragma mark pragma mark UICollectionViewFlowLayoutDelegate CGSize collectionView UICollectionView collectionView layout UICollectionViewLayout collectionViewLayout sizeForItemAtIndexPath NSIndexPath indexPath UIImage image int row indexPath row image UIImage imageNamed carImages row return image size Run the application once again and note that as shown in Figure 52 7 the images are now displayed at their original sizes Figure 52 7 Changing Scroll Direction As currently configured the flow layout object assigned to the collection view is in vertical scrolling mode As a demonstration of both one of the delegate methods for handling user interaction and the effects of horizontal scrolling the example will now be extended to switch to horizontal scrolling when any cell in the view is selected When making changes to the flow layout assigned to a collection view it

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

  • Basic iOS 6 iPad Animation using Core Animation - Techotopia
    to one of a number transformation functions and the result assigned to the transform property of the UIView object For example to change the scale of a UIView 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 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 myView transform CGAffineTransformMakeRotation 90 M PI 180 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 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 CGAffineTransform scaleTrans CGAffineTransformMakeScale 2 2 CGAffineTransform rotateTrans CGAffineTransformMakeRotation angle M PI 180 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 iPad 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 with both product and class prefix named Animate and the Storyboard and Automatic Reference Counting options enabled Implementing the Interface File 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 AnimateViewController h file as follows import UIKit UIKit h interface AnimateViewController UIViewController property nonatomic float scaleFactor property nonatomic float angle property strong nonatomic UIView boxView end 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 initialize our scaleFactor and angle variables and add boxView as a subview of the application s main view object These tasks only need to

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

  • An Overview of iPad iOS 6 Application State Preservation and Restoration - Techotopia
    the Restoration ID field located in the Identity section of the Identity Inspector as illustrated in Figure 57 1 In the case of storyboards the restoration ID can be set to use the storyboard ID if one has already been assigned Figure 57 1 When assigning restoration IDs in Interface Builder it is important to distinguish between views and view controllers Clicking on the white background of view in a storyboard for example will select the UIView object not the view controller Clicking on the black status bar containing the battery life indicator will on the other hand select the view controller As a general rule wherever possible state preservation should be implemented by saving and restoring the state of the view controller which in turn will be responsible for restoring the state of any child view objects Directly saving and restoring the state of individual view objects in a user interface layout should only be performed when preservation requirements cannot be met using the view controller state Default Preservation Features of UIKit Once state preservation has been enabled and restoration identifiers assigned appropriately it is worth being aware that UIKit will preserve certain state information by default and without the need to write any additional code By default the following state information is saved and restored automatically for view controllers Currently presented view controller Currently selected tab State of navigation stacks In the case of views the following is preserved by default Current scroll position Currently selected cell in a table view Current state of an image view zoom pan etc Web history including scroll position and zoom level Additional state preservation will as will be outlined in the remainder of this chapter require some coding Saving and Restoring Additional State Information So far we have ascertained that UIKit will store information about which view controllers and views are to be saved based on whether or not those objects have a restoration ID In many cases each object will have additional information that it needs to save in order to restore the application exactly as the user left it This might for example relate to a specific item the user has selected or some text that has been entered into a Text View but not yet been committed to the application s data model Fortunately UIKit has a way to handle this Once UIKit discovers for example that the state of a specific view controller is to be saved it will check to see if a method named encodeRestorableStateWIthCoder has been implemented in that object s class If the method has been implemented UIKit will call that method passing through a reference to an NSCoder object It is then the responsibility of that method to store any additional state data that needs to be preserved into that NSCoder object before returning UIKit will then save that NSCoder object along with the rest of the application s state When UIKit restores the view controller object on a subsequent launch of

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

  • An iOS 6 iPad State Preservation and Restoration Tutorial - Techotopia
    the Text property Select the Text View object display the Assistant Editor and click and drag from the Text View object to the space beneath the interface line Release the line and in the resulting panel establish a new outlet connection named myTextView Close the Assistant Editor Build and run the application and once running select the second tab and then select and enter some text into the Text View object Place the application into the background and stop the application using the Xcode Stop button Click on run to launch the application again Whilst the selection of the second tab has been preserved the text entered into the Text View has been lost In order to preserve the text entered by the user it will be necessary to implement the encodeRestorableStateWithCoder and decodeRestorableStateWithCoder methods in the parent view controller of the Text View in this case StateAppSecondViewController Select the StateAppSecondViewController m file and add the encoding methods as follows void encodeRestorableStateWithCoder NSCoder coder coder encodeObject myTextView text forKey UnsavedText super encodeRestorableStateWithCoder coder This code is actually very straightforward The method is called by UIKit while the state of the view controller is being saved and is passed an NSCoder object The encodeObject method of the coder methods exist for other types of data as documented in Apple documentation for the NSCoder class is then used to encode the text that is currently held in the myTextView object using a key that will be used to decode the data later The superclass method is then called and the method returns The corresponding decode method also needs to be added void decodeRestorableStateWithCoder NSCoder coder myTextView text coder decodeObjectForKey UnsavedText super decodeRestorableStateWithCoder coder This method simply does the reverse of the encode method It is called by UIKit during the view controller restoration process and passed the NSCoder object containing the saved data The method decodes the text using the previously assigned key and assigns it to the Text View Compile and run the application once again enter some text into the Text View object Place the application into the background before stopping and restarting the application The previously entered text should now be restored and any work entered by the user but not saved has not been lost between application invocations a key objective of iOS state preservation Adding a Navigation Controller to the Storyboard Up until this point in the tutorial all view controllers have resided within a storyboard file As such UIKit has been able to implicitly find and load the controllers at run time The tutorial has so far therefore failed to demonstrate the use of a restoration class to restore a view controller that was created in code as opposed to being stored in a storyboard file The remainder of this chapter will focus on just such a scenario Within the storyboard select the Second view controller and insert a navigation controller using the Editor Embed In Navigation Controller menu option Once added the storyboard should match

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

  • Integrating Maps into iPad iOS 6 Applications using MKMapItem - Techotopia
    code is an example of forward geocoding in that coordinates are calculating based on a text address description Reverse geocoding as the name suggests involves the translation of geographical coordinates into a human readable address string Consider for example the following code CLGeocoder geocoder CLGeocoder alloc init CLLocation newLocation CLLocation alloc initWithLatitude 40 74835 longitude 73 984911 geocoder reverseGeocodeLocation newLocation completionHandler NSArray placemarks NSError error if error NSLog Geocode failed with error error return if placemarks placemarks count 0 CLPlacemark placemark placemarks 0 NSDictionary addressDictionary placemark addressDictionary NSString address addressDictionary objectForKey NSString kABPersonAddressStreetKey NSString city addressDictionary objectForKey NSString kABPersonAddressCityKey NSString state addressDictionary objectForKey NSString kABPersonAddressStateKey NSString zip addressDictionary objectForKey NSString kABPersonAddressZIPKey NSLog address city state zip In this case a CLLocation object is initialized with longitude and latitude coordinates and then passed through to the reverseGeocodeLocation method of a CLGeocoder object The method passes through to the completion handler an array of matching addresses in the form of CLPlacemark objects Each object contains an NSDictionary object which in turn contains the address information for the matching location Once again the code assumes a single match is contained in the array and uses the dictionary keys to access and display the address city state zip and country values The address dictionary keys follow the standard defined in the Address Property section of the iOS SDK Address Book Person reference When executed the above code results in output which reads 338 5th Avenue New York New York 10001 United States It should be noted that the geocoding is not actually performed on the iPad device but rather on a server to which the device connects when a translation is required and the results subsequently returned when the translation is complete As such geocoding can only take place when the iPad has an active internet connection Creating MKPlacemark Instances Each location that is to be represented when a map is displayed using the MKMapItem class must be represented by an MKPlacemark object When MKPlacemark objects are created they must be initialized with the geographical coordinates of the location together with an NSDictionary object containing the address property information Continuing the example for the Empire State Building in New York an MKPlacemark object would be created as follows CLLocationCoordinate2D coords CLLocationCoordinate2DMake 40 74835 73 984911 NSDictionary address NSString kABPersonAddressStreetKey 350 5th Avenue NSString kABPersonAddressCityKey New York NSString kABPersonAddressStateKey NY NSString kABPersonAddressZIPKey 10118 NSString kABPersonAddressCountryCodeKey US MKPlacemark place MKPlacemark alloc initWithCoordinate coords addressDictionary address Whilst it is possible to initialize an MKPlacemark object passing through a nil value for the address dictionary this will result in the map appearing albeit with the correct location marked but it will be tagged as Unknown instead of listing the address The coordinates are however mandatory when creating an MKPlacemark object In the event that the application knows the text address but not the coordinates of a location geocoding will need to be used to obtain the coordinates prior to creating the MKPlacemark instance Working with MKMapItem Given the

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

  • An Example iOS 6 iPad MKMapItem Application - Techotopia
    them to outlets named city state and zip respectively Ctrl click on the Get Directions button and drag the resulting line to a position beneath the new outlets declared in the Assistant Editor In the resulting configuration panel change the Connection type to Action and name the method getDirections On completion the MapItemViewController h file should read as follows import UIKit UIKit h interface MapItemViewController UIViewController property strong nonatomic IBOutlet UITextField address property strong nonatomic IBOutlet UITextField city property strong nonatomic IBOutlet UITextField state property strong nonatomic IBOutlet UITextField zip IBAction getDirections id sender end Converting the Destination using Forward Geocoding When the user touches the button in the user interface the getDirections method will be able to extract the address information from the text fields The objective will be to create an MKPlacemark object to contain this location As outlined in Integrating Maps into iPad iOS 6 Applications using MKMapItem an MKPlacemark instance requires the longitude and latitude of an address before it can be instantiated The first step in the getDirections method is to perform a forward geocode translation of the address Before doing so however it is necessary to declare a property in the MapItemViewController h file in which to store these coordinates once they have been calculated This will in turn require that the CoreLocation CoreLocation h file be imported Now is also an opportune time to import the MapKit MapKit h and AddressBook AddressBook h files both of which will be required later in the chapter import UIKit UIKit h import CoreLocation CoreLocation h import MapKit MapKit h import AddressBook AddressBook h interface MapItemViewController UIViewController property strong nonatomic IBOutlet UITextField address property strong nonatomic IBOutlet UITextField city property strong nonatomic IBOutlet UITextField state property strong nonatomic IBOutlet UITextField zip IBAction getDirections id sender property CLLocationCoordinate2D coords end Next select the MapItemViewController m file locate the getDirections method stub and modify it to convert the address string to geographical coordinates IBAction getDirections id sender CLGeocoder geocoder CLGeocoder alloc init NSString addressString NSString stringWithFormat address text city text state text zip text geocoder geocodeAddressString addressString completionHandler NSArray placemarks NSError error if error NSLog Geocode failed with error error return if placemarks placemarks count 0 CLPlacemark placemark placemarks 0 CLLocation location placemark location coords location coordinate coords location coordinate self showMap The steps used to perform the geocoding translation mirror those outlined in Integrating Maps into iPad iOS 6 Applications using MKMapItem with one difference in that a method named showMap is called in the event that a successful translation took place All that remains therefore is to implement this method Launching the Map With the address string and coordinates obtained the final task is to implement the showMap method This method will create a new MKPlacemark instance for the destination address configure options for the map to request driving directions and then launch the map Since the map will be launched with a single map item it will default to providing directions from the current location With

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



  •