Frequently used code for iPhone Development

Source: Internet
Author: User
Tags response code

 

Change the background of a cell

Uiview * myview = [[uiview alloc] init];
Myview. Frame = cgrecctmake (0, 0,320, 47 );
Myview. backgroundcolor = [uicolor colorwithpatternimage: [uiimage imagenamed: @ "0006.png"];
Cell. selectedbackgroundview = myview;

Add a button on the keyboard:
// Define a message center
[[Nsicationcenter center defacenter center] addobserver: Self selector: @ selector (keyboardwillshow :) name: uikeyboardwillshownotification object: Nil]; // addobserver: registers an observer name: Message name
-(Void) keyboardwillshow :( nsnotification *) Note {
// Create M button
Uibutton * donebutton = [uibutton buttonwithtype: uibuttontypecustom];
Donebutton. Frame = cgrectmake (0,163,106, 53 );
[Donebutton setimage: [uiimage imagenamed: @ "5.png"] forstate: uicontrolstatenormal];
[Donebutton addtarget: Self action: @ selector (addradixpoint) forcontrolevents: uicontroleventtouchupinside];

// Locate keyboard View
Uiwindow * tempwindow = [[[uiapplication sharedapplication] windows] objectatindex: 1]; // return the application window
Uiview * keyboard;
For (INT I = 0; I <[tempwindow. subviews count]; I ++) // traverses all subviews on the window
{
Keyboard = [tempwindow. subviews objectatindex: I];
// Keyboard view found; Add the Custom button to it
If ([[keyboard description] hasprefix: @ "<uikeyboard"] = Yes)
[Keyboard addsubview: donebutton];
}
}

Regular Expressions:
The string used for the regular expression must be variable-length. Otherwise, problems may occur.

Place a space on a view
[Scrollview insertsubview: searchbutton abovesubview: scrollview];

Attach images locally
Nsstring * boundle = [[nsbundle mainbundle] resourcepath];
[Web1 loadhtmlstring: [nsstring stringwithformat: @ "

Load images from webpages and narrow down images in specified lengths and widths
[Cell. IMG loadhtmlstring: [nsstring stringwithformat: @ "<HTML> <body> </body> Load the webpage to webview and obtain the data through javascript. If you send a connection request to obtain the source code, you can use a regular expression to obtain the data.
Nsstring * javascript1 = @ "document. getelementsbyname ('. U'). Item (0). Value ";
Nsstring * javascript2 = @ "document. getelementsbyname ('. Challenge'). Item (0). Value ";
Nsstring * strresult1 = [nsstring stringwithstring: [thewebview stringbyevaluatingjavascriptfromstring: javascript1];
Nsstring * strresult2 = [nsstring stringwithstring: [thewebview stringbyevaluatingjavascriptfromstring: javascript2];

How to convert utf8 to Unicode using nsstring
Utf8str //
Nsstring * unicodestr = [nsstring stringwithcstring: [utf8str utf8string] encoding: nsunicodestringencoding];

View calls its own method:
[Self defined mselector: @ selector (logintonext) withobject: Nil afterdelay: 2]; // The Yellow segment is the method name, And the execution delay is several seconds.

Display image:
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; // whether opaque is transparent
[Self. View addsubview: myimage];
[Myimage release];

Webview:
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];

Network Activity Status Indicator
This is a rotating icon displayed in the status bar on the upper left of the iPhone, indicating that a network activity occurs on the background.
Uiapplication * APP = [uiapplication sharedapplication];
App. networkactivityindicatorvisible = yes;

Animation: displays a series of images one by one
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; // The animationimages attribute returns an array of animation images.
Myanimatedview. animationduration = 0.25; // time used to browse the entire image
Myanimatedview. animationrepeatcount = 0; // 0 = number of times the loops forever animation is repeated
[Myanimatedview startanimating];
[Self addsubview: myanimatedview];
[Myanimatedview release];

Animation: Something is displayed moving on the screen. Note: This type of animation is "not processed after the start"-you cannot obtain any information about the object in the animation (such as the current position ). If you need this information, you will manually use the timer to adjust the X and Y coordinates of the animation.
Import quartzcore. framework.
Cabasicanimation * theanimation;
Theanimation = [cabasicanimation animationwithkeypath: @ "transform. Translation. X"];
// Creates and returns an capropertyanimation instance for the specified key path.
// Parameter: the Key Path of the property to be animated
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 // drag a project
Here's how to create a simple draggable image. // This is how to generate a simple drag 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 retrieval touchpoint
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 to move relative to the previous 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
// Put the new class of the instance to your view.
Dragger = [[mydraggableimage alloc] initwithframe: mydragrect];
[Dragger setimage: [uiimage imagenamed: @ "myimage.png"];
[Dragger setuserinteractionenabled: Yes];

Thread:
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];

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
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}
}

View response code such as uiimageview

Self. userinteractionenabled = true;

-(Void) touchesbegan :( nsset *) touches withevent :( uievent *) event
{
Uitouch * Touch = [touches anyobject];
If ([Touch view] = m_view) // determines which view responds to the operation
{

[Self playvedio];
}

}

Note: Self. userinteractionenabled = true; enables a view to accept events.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.