Logging
In xcode, click Run> console to see nslog statements.
Nslog (@ "log: % @", mystring );
Nslog (@ "log: % F", myfloat );
Nslog (@ "log: % I", Myint );
Display images
Display an image anywhere on the screen, without using UI builder. You can use this for other types of views as well.
Cgrect myimagerect = cgrectmake (0.0f, 0.0f, 3200000f, 109.0f );
Uiimageview * myimage = [[uiimageview alloc] initwithframe: myimagerect];
[Myimage setimage: [uiimage imagenamed: @ "myimage.png"];
Myimage. opaque = yes;
// Explicitly opaque for performance
[Self. View addsubview: myimage];
[Myimage release];
Web View
A basic uiwebview.
Cgrect webframe = cgrectmake (0.0, 0.0, 320.0, 460.0 );
Uiwebview * webview = [[uiwebview alloc] initwithframe: webframe];
[Webview setbackgroundcolor: [uicolor whitecolor];
Nsstring * urladdress = @ "http://www.google.com ";
Nsurl * url = [nsurl urlwithstring: urladdress];
Nsurlrequest * requestobj = [nsurlrequest requestwithurl: url];
[Webview loadrequest: requestobj];
[Self addsubview: webview];
[Webview release]; display the network activity status indicator
This is the rotating icon displayed on the iPhone status bar in the upper left to indicate there is background network activity taking place.
Uiapplication * APP = [uiapplication sharedapplication];
App. networkactivityindicatorvisible = yes; // to stop it, set this to no
Animation: series of images
Show a series of images in succession
Nsarray * myimages = [nsarray images: [uiimage imagenamed: @ "myimage1.png"], [uiimage imagenamed: @ "myimage2.png"], [uiimage imagenamed: @ "myimage3.png"], [uiimage imagenamed: @ "myimage4.gif"], nil];
Uiimageview * myanimatedview = [uiimageview alloc];
[Myanimatedview initwithframe: [self bounds];
Myanimatedview. animationimages = myimages;
Myanimatedview. animationduration = 0.25; // seconds
Myanimatedview. animationrepeatcount = 0; // 0 = loops forever
[Myanimatedview startanimating];
[Self addsubview: myanimatedview];
[Myanimatedview release];
Animation: Move an object
Show something moving implements ss the screen. note: This type of animation is "fire and forget" -- you cannot obtain any information about the objects during animation (such as current position ). if you need this information, you will want to animate manually using a timer and adjusting the X & Y coordinates as necessary.
Import quartzcore. framework.
Cabasicanimation * theanimation;
Theanimation = [cabasicanimation animationwithkeypath: @ "transform. Translation. X"];
Theanimation. Duration = 1;
Theanimation. repeatcount = 2;
Theanimation. autoreverses = yes;
Theanimation. fromvalue = [nsnumber numberwithfloat: 0];
Theanimation. tovalue = [nsnumber numberwithfloat:-60];
[View. layer addanimation: theanimation forkey: @ "animatelayer"];
Draggable items
Here's how to create a simple draggable image.
1. Create a new class that inherits from uiimageview
@ Interface mydraggableimage: uiimageview {}
2. In the implementation for this new class, add the 2 methods:
-(Void) touchesbegan :( nsset *) touches withevent :( uievent *) event
{// Retrieve the touch point
Cgpoint Pt = [[touches anyobject] locationinview: Self];
Startlocation = pt;
[[Self superview] bringsubviewtofront: Self];
}
-(Void) touchesmoved :( nsset *) touches withevent :( uievent *) event
{// Move relative to the original touch point
Cgpoint Pt = [[touches anyobject] locationinview: Self];
Cgrect frame = [self frame];
Frame. Origin. x + = pt. X-startlocation. X;
Frame. Origin. Y + = pt. Y-startlocation. Y;
[Self setframe: frame];
}
3. Now instantiate the new class as you wowould any other new image and add it to your view
Dragger = [[mydraggableimage alloc] initwithframe: mydragrect];
[Dragger setimage: [uiimage imagenamed: @ "myimage.png"];
[Dragger setuserinteractionenabled: Yes];
Vibration and sound
Here is how to make the phone vibrate (Note: Vibration does not work in the simulator, it only works on the device .)
Audioservicesplaysystemsound (ksystemsoundid_vibrate );
Sound will work in the simulator, however some sound (such as looped) has been reported as not working in simulator or even altogether depending on the audio format. note there are specific filetypes that must be used (.wav in this example ).
Systemsoundid pmph;
Id sndpath = [[nsbundle mainbundle] pathforresource: @ "mysound" oftype: @ "WAV" indirectory: @ "/"];
Cfurlref baseurl = (cfurlref) [[nsurl alloc] initfileurlwithpath: sndpath];
Audioservicescreatesystemsoundid (baseurl, & pmph );
Audioservicesplaysystemsound (pmph );
[Baseurl release];
Threading
1. Create the new thread:
[Nsthread detachnewthreadselector: @ selector (mymethod) totarget: Self withobject: Nil];
2. Create the method that is called by the new thread:
-(Void) mymethod
{
NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init];
*** Code that shoshould be run in the new thread goes here ***
[Pool release];
}
What if you need to do something to the main thread from inside your new thread (for example, show a loading symbol )? Use your mselecdomainmainthread.
[Self defined mselecw.mainthread: @ selector (mymethod) withobject: Nil waituntildone: false];
Timers
This timer will call mymethod every 1 second.
[Nstimer scheduledtimerwithtimeinterval: 1 target: Self selector: @ selector (mymethod) userinfo: Nil repeats: Yes];
2. then pass the nstimer object to your method:
-(Void) mymethod :( nstimer *) Timer
{
// Now I can access all the properties and methods of myobject
[[Timer userinfo] myobjectmethod];
}
3. To stop a timer, use "invalidate ":
[Mytimer invalidate]; mytimer = nil; // ensures we never invalidate an already invalid Timer
Plist files
Application-specific plist files can be stored in the resources folder of the app bundle. when the app first launches, it shocould check if there is an existing plist in the user's orders ents folder, and if not it shocould copy the plist from the app bundle.
// Look in statements for an existing plist File
Nsarray * paths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes );
Nsstring * documentsdirectory = [paths objectatindex: 0];
Myplistpath = [documentsdirectory stringbyappendingpathcomponent:
[Nsstring stringwithformat: @ "% @. plist", plistname];
[Myplistpath retain];
// If it's not there, copy it from the bundle
Nsfilemanager * filemanger = [nsfilemanager defaultmanager];
If (! [Filemanger fileexistsatpath: myplistpath])
{
Nsstring * pathtosettingsinbundle = [[nsbundle mainbundle] pathforresource: plistname oftype: @ "plist"];
}
Now read the plist file from documents ents
Nsarray * paths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes );
Nsstring * documentsdirectorypath = [paths objectatindex: 0];
Nsstring * Path = [documentsdirectorypath stringbyappendingpathcomponent: @ "MyApp. plist"];
Nsmutabledictionary * plist = [nsdictionary dictionarywithcontentsoffile: path];
Now read and set key/Values
Mykey = (INT) [[plist valueforkey: @ "mykey"] intvalue];
Mykey2 = (bool) [[plist valueforkey: @ "mykey2"] boolvalue];
[Plist setvalue: mykey forkey: @ "mykey"];
[Plist writetofile: path atomically: Yes];
Alerts
Show a simple alert with OK button.
Uialertview * Alert = [[uialertview alloc] initwithtitle: Nil message:
@ "An alert! "Delegate: Self cancelbuttontitle: @" OK "otherbuttontitles: Nil];
[Alert show];
[Alert release];
Info button
Increase the touchable area on the info button, so it's easier to press.
Cgrect newinfobuttonrect = cgrectmake (infobutton. frame. origin. x-25, infobutton. frame. origin. y-25, infobutton. frame. size. width + 50, infobutton. frame. size. height + 50 );
[Infobutton setframe: newinfobuttonrect];
Detecting subviews
You can loop through subviews of an existing view. This works especially well if you use the "tag" property on your views.
For (uiimageview * animage in [self. View subviews])
{
If (animage. Tag = 1)
{// Do something}
}