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".
  • IPhone Rotation, View Resizing and Layout Handling - Techotopia
    to gain an appreciation of the importance of handling orientation changes save the design and build and run the application Once the simulator appears rotate the device by 90⁰ Because we have enabled rotation the view will rotate to the landscape orientation Here we see a classic example of the implications of enabling rotation in an application without taking the additional steps to reformat the view to match the change in orientation Having rotated the device only the top button is visible and it is still centered assuming that the device is in portrait mode The second button is similarly positioned resulting in it being outside the viewable area of the screen In order to ensure the correct layout of the user interface it is necessary to make some changes to the autosize settings of the two buttons The current settings for a view are accessed from within Interface Builder by selecting the component and displaying the Size Inspector Tools Size Inspector or Command 3 The following figure shows the Size Inspector for the top button in our user interface The section of this window that is of interest to us is the area entitled Autosizing and in particular the white box on the left The outer box represents the superview and the inner box represents the subview that is contained within the superview Any autosizing settings that are configured on a subview are relative to the superview Within the subview box are two intersecting lines with arrows at each end These vertical and horizontal lines indicate whether the height and width of the selected view object should increase or decrease in proportion to size changes in the corresponding superview A faint dotted line indicates that the currently selected view object is not to resize in relation to the superview A solid red line on the other hand indicates that it should resize proportionally to the parent view The graphic to the right of the white box provides a visual representation of how the view will behave based on the current settings The red box represents the subview and the white box represents the containing superview Click on the horizontal line to change it to solid red and see how the width of the red box representing the button grows and shrinks as the containing superview size changes Similarly enable resizing for the height of the button and observe how the height of the button also now changes proportionally to the superview google IOSBOX google These two settings correspond to the UIViewAutoResizingFlexibleHeight and UIViewAutoResizingFlexibleWidth autoresizing mask properties The lines separating the four sides of the inner subview and the outer superview boxes are referred to as struts and control what happens to the margin between each side of the subview and the corresponding sides of the superview when the latter resizes as the result of an orientation change When a strut is enabled indicated by the solid red lines the corresponding margin remains fixed when the superview resizes In the

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


  • Creating an iPhone Multiview Application using the Tab Bar - Techotopia
    view will need a view controller and a NIB file to contain the user interface To create these right click over the Classes category located in the Groups and Files panel on the left hand side of the main Xcode project window and select Add New File This will display the template selection screen as illustrated in the following figure In the left hand panel verify that the iPhone OS Cocoa Touch Class option is selected and that the current selection in the main panel is the UIViewController subclass icon Since we also need an Interface Builder NIB file make sure that the With XIB for Interface Builder option is selected before clicking on the Next button On the following screen specify ScreenOneViewController m as the file name and verify that the Also create ScreenOneViewController h option is selected Click Finish to create the new view controller class files and corresponding Interface Builder file Repeat the above procedure to create the second content view and view controller this time using the name ScreenTwoViewController Configuring the App Delegate The next class we are going to add to our project is the root controller Before we do so however we need to add an outlet to this controller within the app delegate file and also add some code to the applicationDidFinishLoading method to add the view instance of the root controller as a subview of the application s main window Select the TabBar item at the top of the Groups and Files panel so that all the files in the project are listed Select the TabBarAppDelegate h file and modify it as follows in the editing panel import UIKit UIKit h interface TabBarAppDelegate NSObject UIApplicationDelegate UITabBarController tabController UIWindow window property nonatomic retain IBOutlet UIWindow window property nonatomic retain IBOutlet UITabBarController tabController end Next edit the TabBarAppDelegate m implementation file and modify the code as follows import TabBarAppDelegate h implementation TabBarAppDelegate synthesize tabController synthesize window void applicationDidFinishLaunching UIApplication application Override point for customization after application launch window addSubview tabController view window makeKeyAndVisible void dealloc tabController release window release super dealloc end Now that we have made the appropriate additions to the app delegate sub class we can now add the root view controller to the project Creating the UITabBarController google IOSBOX google As previously mentioned because we are designing a tab bar based multiview application it makes sense for us to the an instance of the UITabBarController class as the root controller This is achieved from within MainWindow xib so double click on this file to load it into Interface Builder From within the Library window click and drag a Tab Bar Controller object over to a blank area of the MainWindow xib window Once the object has been added the list of items in the MainWindow xib window should appear as follows As shown in the above figure the Tab Bar Controller is now listed amongst the items in the MainWindow xib file and a new window entitled Tab Bar Controller now

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

  • Creating a Simple iPhone Table View Application - Techotopia
    to the File s Owner icon located in the TableExampleViewController xib document window Once the connection is established repeat this task for the delegate outlet The connections should now be displayed as follows Now that the connections have been established save the file and exit from Interface Builder Implementing the dataSource In order to bring our table view application to life we need to implement two dataSource methods in our view controller Before doing so however we need to create the data itself In this example we are going to create NSArray object and initialize it with some strings In the main Xcode project window select the TableExampleViewController h file and modify it in the editing pane to declare the array import UIKit UIKit h interface TableExampleViewController UIViewController UITableViewDelegate UITableViewDataSource NSArray colorNames property nonatomic retain NSArray colorNames end Note the references to UITableViewDelegate and UITableViewDataSource in the above code These are included to notify the Objective C compiler that the class implements these two protocols Consequently if we fail to implement the mandatory methods required by these protocols the compiler will notify us with a warning If this line is omitted from the class declaration the code will still compile but we not be warned if we have failed to implement any methods The only indication we will get will the application crashing at run time For this reason including these declarations is generally considered to be good programming practice Next edit the TableExampleViewController m class implementation file to synthesize access to the array import TableExampleViewController h implementation TableExampleViewController synthesize colorNames end Now that we have declared our array we need to initialize it with some data when the view is loaded In order to achieve this we will override the viewDidLoad method Scroll down the TableExampleViewController m file until you find the template method uncomment it by removing the and markers and modify the method as follows Implement viewDidLoad to do additional setup after loading the view typically from a nib void viewDidLoad super viewDidLoad self colorNames NSArray alloc initWithObjects Red Green Blue Indigo Violet nil Having allocated memory to our array and initialized it the next task is to make sure the memory gets released when the array is no longer required To do so it is necessary to add code to the viewDidUnload and dealloc methods void viewDidUnload Release any retained subviews of the main view e g self myOutlet nil self colorNames nil void dealloc colorNames release super dealloc With our data constructed all we need to do now is implement the numberOfRowsInSection and cellForRowAtIndexPath methods in order to conform to the minimum requirements of the UITableViewDataSource protocol We will begin by implementing the numberOfRowsInSection method which is called by the Table View to identify how many rows are to be displayed Since our data is held in an array we can simply return the number of array elements to satisfy this requirement so add the following method to your TableExampleViewController m file Customize the number

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

  • Creating a Navigation based iPhone Application using TableViews - Techotopia
    call to the numberOfRowsInSection method Our RootViewController m file contains a pre created template of this method currently coded to return 0 In our example we want to return a value equivalent to the number of items in our authorList array so we need to modify this method accordingly NSInteger tableView UITableView tableView numberOfRowsInSection NSInteger section return self authorList count Having identified the number of items to be displayed the table view then needs to get a UITableViewCell object containing the data to be displayed for each row It achieves this by calling the cellForRowAtIndexPath method for each row passing through the current row as an argument When called this method identifies the row being requested and constructs and returns a cell object Implement the code to return a table cell for each row of the table view by modifying the template method as follows UITableViewCell tableView UITableView tableView cellForRowAtIndexPath NSIndexPath indexPath static NSString CellIdentifier Cell UITableViewCell cell tableView dequeueReusableCellWithIdentifier CellIdentifier if cell nil cell UITableViewCell alloc initWithStyle UITableViewCellStyleDefault reuseIdentifier CellIdentifier autorelease Configure the cell cell textLabel text self authorList objectAtIndex indexPath row return cell Note that Xcode has already written most of the code for us In fact the only line we have to add is as follows cell textLabel text self authorList objectAtIndex indexPath row This line of code simply identifies the row that has been requested uses it as the index into our array of authors and assigns it to the appropriate property of the cell object that was created for us in the preceding lines of the method Now is a good time to make sure we haven t made any errors in our coding so build and run the application to make sure it all works so far Assuming all is well the application should appear in the simulator as follows When we click on an author we want to navigate to another table view that provides a list of books written by that author That table view will have its own NIB file containing the table view object and also its own view controller The next steps therefore are to create these two files and configure them to meet our requirements Creating the Second View Controller google IOSBOX google To create the view controller for the table view that will display the list of books written by the selected author right click on Classes under Groups Files in the main Xcode project window and select Add New File On the template selection screen select iPhone OS Cocoa Touch Class followed by the UIViewController subclass icon Make sure that the UITableViewController subclass option is selected We will manually create the NIB file later so leave the With XIB for user interface option unchecked Click on Next and name the class BooksViewController Since we will need an interface header file leave the Also create BooksViewController h option selected and click Finish to create the files Before we begin work on our second table view we need to make sure that the new class is declared within our root view controller class To do so edit the RootViewController h file and add code to forward reference the BooksViewController class and add an outlet to the new view controller import booksViewController h class BooksViewController interface RootViewController UITableViewController NSArray authorList BooksViewController booksController property nonatomic retain IBOutlet BooksViewController booksController property nonatomic retain NSArray authorList end Before we move on to the next step be sure to save the above changes to the RootViewContoller h file by selecting File Save so that the outlet is visible to us from inside Interface Builder Failure to save the file at this point may result in the outlet not appearing when we try to create connections from within Interface Builder Connecting the Second View Controller to the Root View Controller Load RootViewController xib into Interface Builder and drag a new View Controller UIViewController object from the Library window Tools Library or Command L to the RootViewController xib document window Open the Identity Inspector Tools Identity Inspector or Command 4 and change the Class from UIViewController to BooksViewController Select the File s Owner icon and open the Connections Inspector Tools Connections Inspector or Command 2 Ctrl click in the circle located to the right of the booksController outlet and drag the blue line to the Books View Controller item in the RootViewController xib window to make the connection to the outlet Save the design and exit from Interface Builder Creating the NIB File for the Second Table View The next step is to create the NIB file for our second view controller This will contain the instance of the table view that we will use to display the books that the selected author has written In the main Xcode window right click on the Resources entry listed in the Groups Files panel and select Add New File In the New File dialog select User Interface under the iPhone OS list and select the View XIB icon in the main panel Click Next and name the file BooksViewController xib before clicking the Finish button to create the file Double click on BooksViewController xib in the main project window to load it into Interface Builder The file currently contains a UIView object when we actually want it to contain a UITableView In the BooksViewController xib document window select the View icon and press the Delete key on the keyboard to remove it from the file From the Library window Tools Library or Command L drag a Table View object into the document window The design window will subsequently update to reflect the presence of the table view populating it with some dummy data Select the File s Owner icon display the Identity Inspector and change the class to BooksViewController With the File s Owner item still selected display the Connections Inspector Tools Connections Inspector or Command 2 Click on the circle to the right of the view outlet and drag to the Table View entry in the

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

  • Working with Directories on iPhone OS - Techotopia
    Working Directory As previously mentioned when an application first loads its current working directory is the application s root directory represented by a character The current working directory may be identified at any time through a call to the currentDirectoryPath method of the file manager object For example the following code fragment identifies the current working directory NSFileManager filemgr NSString currentPath filemgr NSFileManager defaultManager currentPath filemgr currentDirectoryPath filemgr release In this code we declare a new object named filemgr that is an instance of the NSFileManager class and also an NSString object named currentPath to contain the current working directory path Having created a file manager instance we then call the currentDirectoryPath method of that instance and assign the resulting string to currentPath Identifying the Documents Directory Each iPhone application on a device has its own private Documents and tmp directories into which it is permitted to read and write data Because the location of these directories is different for each application the only way to find the correct path is to ask the iPhone OS In fact the exact location will also differ depending on whether the application is running on a physical iPhone device or in the simulator The Documents directory for an application may be identified by making a call to a C function named NSSearchPathForDirectoriesInDomains passing through an argument in this case NSDocumentDirectory indicating that we require the path to the Documents directory Since this is a C function as opposed to a method of an Objective C class there is no need for us to establish an instance of a Foundation class such as NSFileManager before making the call That said the function does return an object in the form of an NSArray containing the results of the request We can therefore obtain the path to the current application s Documents directory as follows NSArray dirPaths NSString docsDir dirPaths NSSearchPathForDirectoriesInDomains NSDocumentDirectory NSUserDomainMask YES docsDir dirPaths objectAtIndex 0 When executed the above code will assign the path to the Documents directory to the docsDir string When executed within the iPhone simulator environment the path returned will take the form of Users user name Library Application Support iPhone Simulator User Application app id Documents Where user name is the name of the user currently logged into the Mac OS X system on which the simulator is running and app id is the unique ID of the app for example 06A3AEBA 8C34 476E 937F A27BDD2E450A Clearly this references a path on your Mac OS X system so feel free to open up a Finder window and explore the file system sandbox areas for your applications When executed on a physical iPhone device the path returned by the function call will take the following form var mobile Applications app id Documents Identifying the Temporary Directory In addition to the Documents directory iPhone applications are also provided with a tmp directory for the storage of temporary files The path to the current application s temporary directory may be ascertained with

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

  • Working with Files on the iPhone - Techotopia
    filemgr release Removing a File The removeItemAtPath method removes the specified file from the file system The method takes as arguments the pathname of the file to be removed and an optional NSError object The success of the operation is as usual reported in the form of a boolean YES or NO return value NSFileManager filemgr filemgr NSFileManager defaultManager if filemgr removeItemAtPath tmp myfile txt error NULL YES NSLog Remove successful else NSLog Remove failed filemgr release Creating a Symbolic Link A symbolic link to a particular file may be created using the createSymbolicLinkAtPath method This takes as arguments the path of the symbolic link the path to the file to which the link is to refer and an optional NSError object For example the following code creates a symbolic link from Users demo file1 txt that links to the pre existing file tmp myfile txt NSFileManager filemgr filemgr NSFileManager defaultManager if filemgr createSymbolicLinkAtPath Users demo file1 txt withDestinationPath tmp myfile txt error NULL YES NSLog Remove successful else NSLog Remove failed filemgr release Reading and Writing Files with NSFileManager The NSFileManager class includes some basic file reading and writing capabilities These capabilities are somewhat limited when compared to the options provided by the NSFileHandle class but can be useful nonetheless Firstly the contents of a file may be read and stored in an NSData object through the use of the contentsAtPath method NSFileManager filemgr NSData databuffer filemgr NSFileManager defaultManager databuffer filemgr contentsAtPath tmp myfile txt Having stored the contents of a file in an NSData object that data may subsequently be written out to a new file using the createFileAtPath method databuffer filemgr contentsAtPath tmp myfile txt filemgr createFileAtPath tmp newfile txt contents databuffer attributes nil filemgr release google ADSDAQBOX FLOW google In the above example we have essentially copied the contents from an existing file to a new file This however gives us no control over how much data is to be read or written and does not allow us to append data to the end of an existing file If the file tmp newfile txt in the above example had already existed it and any data it contained would have been overwritten by the contents of the source file Clearly some more flexible mechanism is required This is provided by the Foundation Framework in the form of the NSFileHandle class Working with Files using the NSFileHandle Class The NSFileHandle class provides a range of methods designed to provide a more advanced mechanism for working with files In addition to files this class can also be used for working with devices and network sockets In the following sections we will look at some of the more common uses for this class Creating an NSFileHandle Object An NSFileHandle object can be created when opening a file for reading writing or updating reading and writing This is achieved using the fileHandleForReadingAtPath fileHandleForWritingAtPath and fileHandleForUpdatingAtPath methods respectively Having opened a file it must subsequently be closed when we have finished working

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

  • IPhone OS Directory Handling and File I/O – A Worked Example - Techotopia
    of a button and a text field To begin the user interface design process double click on the FileExampleViewController xib file to launch the Interface Builder tool Once the tool has started drag a UIButton and then a UITextField from the Library window Tools Library onto the view Double click on the button and change the text to Save Position the components and resize the width of the text field so that the layout appears as illustrated in the following figure The next step is to establish the connections between the user interface components and the action and outlet created in the view controller code Open the Connections Inspector window by selecting the Tools Connections Inspector menu option or by pressing Command 2 on the keyboard and select the button object in the view window so that the available events for that object are listed in the connections inspector window Click in the small circle to the right of the Touch Up Inside event and drag the blue line to the File s Owner entry in the documents window Release the mouse button and select the saveText action method from the resulting menu to create the connection To connect the text field to the textBox outlet declared in the view controller interface file press and hold the control key click with the mouse over the File s Owner and drag the blue line to the text field object in the view window Release and select the textBox entry from the resulting menu The user interface design is now complete and the connections are now established Save the design File Save and exit from Interface Builder Interface Builder Quit Interface Builder Checking the Data File on Application Startup Each time the application is launched by the user we need to check to see if the data file already exists if the user has not previously saved any text the file will not have been created If the file does exist the contents need to be read by the application and displayed within the text field A good place to put initialization code of this nature is in the viewDidLoad method of the view controller With this in mind select the FileExampleViewController m file and scroll down to the viewDidLoad method Remove the comment markers from around the method and edit it as follows Implement viewDidLoad to do additional setup after loading the view typically from a nib void viewDidLoad NSFileManager filemgr NSString dataFile NSString docsDir NSArray dirPaths filemgr NSFileManager defaultManager Identify the documents directory dirPaths NSSearchPathForDirectoriesInDomains NSDocumentDirectory NSUserDomainMask YES docsDir dirPaths objectAtIndex 0 Build the path to the data file dataFile docsDir stringByAppendingPathComponent datafile dat Check if the file already exists if filemgr fileExistsAtPath dataFile Read file contents and display in textBox NSData databuffer databuffer filemgr contentsAtPath dataFile NSString datastring NSString alloc initWithData databuffer encoding NSASCIIStringEncoding textBox text datastring datastring release filemgr release super viewDidLoad Before proceeding we need to take some time to talk about what the above code is

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

  • IPhone Data Persistence using Archiving - Techotopia
    IBOutlet UITextField address property nonatomic retain IBOutlet UITextField phone property nonatomic retain NSString dataFilePath IBAction saveData end Having made the appropriate declarations in the interface file the next step is to move to the archiveViewController m implementation file where we will synthesize the access methods for our instance variables and create a template method for the saveData action import archiveViewController h implementation archiveViewController synthesize name address phone dataFilePath void saveData end We will need to do some more coding later but at this point it makes sense to design the user interface and establish the connections between the user interface object and the outlets and action we have declared so far Releasing Memory Having allocted memory in implementing the above outlets it is important that we add code to free up any resources that were allocated during execution of the application To do so edit the archiveViewController m file again and modify the viewDidUnload and dealloc methods as follows void viewDidUnload Release any retained subviews of the main view e g self myOutlet nil self name nil self address nil self phone nil self dataFilePath nil void dealloc name release address release phone release dataFilePath release super dealloc Designing the User Interface The user interface for our application is going to consist of three UILabels three UITextFields and single UIButton Launch the Interface Builder tool by double clicking on the archiveViewController xib in the main Xcode project window Display the tool s Library window if it is not already visible by selecting the Tools Library menu option or by pressing Command L Drag drop resize position and configure objects on the View window canvas until your design approximates that illustrated in the following figure The next step is to establish the connections to our action and outlets Beginning with the outlets hold down the Ctrl key and click and drag from the File s Owner item in the documents window to the text field component located to right of the Name label object Release the Ctrl key and mouse button and select the name outlet from the resulting menu Repeat these steps for the address and phone text fields connecting them to the corresponding outlets To connect the action select the Save button object in the view window and display the Connections Inspector window Tools Connections Inspector or Command 2 Click with the mouse within the small round circle to the right of the Touch Up Inside event and drag the blue line to the File s Owner entry in the documents window Release the mouse button and select the saveData method from the resulting window Having designed the user interface and established the necessary connections save the design and exit from Interface Builder Checking for the Existence of the Archive File on Startup Each time the application is launched by the user the code will need to identify whether the archive data file exists from a previous session In the event that it does exist the archive will need

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



  •