IPHONE開発常用方法

16928 ワード

転載:http://blog.csdn.net/pzw0416/article/details/7577836
 
入力キーボードを戻す:
- (BOOL) textFieldShouldReturn:(id)textField{
    [textField  resignFirstResponder];
}
CGRect
CGRect frame = CGRectMake (origin.x, origin.y, size.width, size.height);  
NSStringFromCGRect(someCG)  CGRect           ;
CGRectFromString(aString)          ;
CGRectInset(aRect)           (     ),+    -  
CGRectIntersectsRect(rect1, rect2)          ,    
CGRectZero         /  (0,0)     
CGPoid&CGS ize
CGPoint aPoint = CGPointMake(x, y);    CGSize aSize = CGSizeMake(width, height);
透明度を設定
 [myView setAlpha:value];   (0.0 < value < 1.0)
背景色を設定
 [myView setBackgroundColor:[UIColor redColor]];
   (blackColor;darkGrayColor;lightGrayColor;whiteColor;grayColor; redColor; greenColor; blueColor; cyanColor;yellowColor;magentaColor;
orangeColor;purpleColor;brownColor; clearColor; )
カスタム色:
UIColor *newColor = [[UIColor alloc] initWithRed:(float) green:(float) blue:(float) alpha:(float)];      0.0~1.0
幅と高さ
768X1024     1024X768         20               44   
ステータスバーを隠す:
[[UIApplication shareApplication] setStatusBarHidden: YES animated:NO]
横パネル:
[[UIApplication shareApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight].
orientation == UIInterfaceOrientationLandscapeLeft
window=[[UIWindow alloc] initWithFrame:[UIScreen mainScreen] bounds];  
親ビューのサイズに自動的に合わせる:
aView.autoresizingSubviews = YES;
aView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
定義ボタン
UIButton *scaleUpButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[scaleUpButton setTitle:@"   " forState:UIControlStateNormal];
scaleUpButton.frame = CGRectMake(40, 420, 100, 40);
[scaleUpButton addTarget:self action:@selector(scaleUp) forControlEvents:UIControlEventTouchUpInside];
ビューの背景画像を設定
UIImageView *aView;
[aView setImage:[UIImage imageNamed:@”name.png”]];
view1.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"image1.png"]];

UISlider *slider = (UISlider *) sender;
NSString *newText = [[NSString alloc] initWithFormat:@”%d”, (int)(slider.value + 0.5f)];
label.text = newText;
アクティブフォーム
 - (IBActive) someButtonPressed:(id) sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                    initWithTitle:@”Are you sure?”
                    delegate:self
                    cancelButtonTitle:@”No way!”
                    destructiveButtonTitle:@”Yes, I’m Sure!”
                    otherButtonTitles:nil];
    [actionSheet showInView:self.view];
    [actionSheet release];
}
警告表示
 - (void) actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger) buttonIndex
{
     if(buttonIndex != [actionSheet cancelButtonIndex])
     {
          NSString *message = [[NSString alloc] initWithFormat:@”You can
                   breathe easy, everything went OK.”];
          UIAlertView *alert = [[UIAlertView alloc]
                               initWithTitle:@”Something was done”
                                message:message
                                delegate:self
                                cancelButtonTitle:@”OK”
                                otherButtonTitles:nil];
          [alert show];
          [alert release];
          [message release];
     }
}
アニメーション効果
-(void)doChange:(id)sender
{
if(view2 == nil)
{
[self loadSec];
}
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[UIView setAnimationTransition:([view1 superview] ? UIViewAnimationTransitionFlipFromLeft : UIViewAnimationTransitionFlipFromRight)forView : self.view cache:YES];

    if([view1 superview]!= nil)
{
[view1 removeFromSuperview];
[self.view addSubview:view2];

}else {

[view2 removeFromSuperview];
[self.view addSubview:view1];
}
[UIView commitAnimations];
}
Table View<UItable View DateSource>
#pragma mark -
#pragma mark Table View Data Source Methods
//        ,   1
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}

//     cell     
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIndentifier = @"SimpleTableIndentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIndentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:SimpleTableIndentifier]
autorelease];
}
     UIImage *image = [UIImage imageNamed:@"13.gif"];
cell.imageView.image = image;

NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
     cell.textLabel.font = [UIFont boldSystemFontOfSize:20];

     if(row < 5)
cell.detailTextLabel.text = @"Best friends";
else
    cell.detailTextLabel.text = @"friends";
return cell;
}
画像:画像を設定するとテキストの左側に表示されます。
テキストラベル:これはユニットの主要テキストです。
詳細テキストラベル:これはユニットの補助テキストで、説明またはラベルとして一般的に使われています。
UITableViewCellStyleSubtitle
UITableViewCellStyleDefault
UITableViewCellStyleValue1
UITableViewCellStyleValue2

<UITableViewDelegate>
#pragma mark -
#pragma mark Table View Delegate Methods
//              
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
return row;
}
//       indexPath 
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
if (row == 0)
return nil;
return indexPath;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
NSString *rowValue = [listData objectAtIndex:row];
NSString *message = [[NSString alloc] initWithFormat:@"You selected %@",rowValue];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Row Selected"
message:message
    delegate:nil
  cancelButtonTitle:@"Yes, I did!"
  otherButtonTitles:nil];
[alert show];
[alert release];
[message release];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//      
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40;
}
乱数の使用
              
        #import <time.h>
        #import <mach/mach_time.h>

        srandom()   
        srandom((unsigned)(mach_absolute_time() & 0xFFFFFFFF));

             random()       
UImageViewで画像を回転させる
        float rotateAngle = M_PI;
        CGAffineTransform transform =CGAffineTransformMakeRotation(rotateAngle);
        imageView.transform = transform;
以上のコードはimagViewを回転して、角度はrotateAngleで、方向は自分でテストすることができます。
Quartzではどのように回転点を設定しますか?
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg.png"]];
        imageView.layer.anchorPoint = CGPointMake(0.5, 1.0);
これは回転点を底の中間に設定します。覚えておくと、QuartzCore.frame ewarkでサポートされます。
ファイルを作成して保存します。
        NSString *errorDesc;  //        
        NSMutableDictionary *rootObj = [NSMutableDictionary dictionaryWithCapacity:4]; //NSDictionary, NSData          plist  
        NSDictionary *innerDict;
        NSString *name;
        Player *player;
        NSInteger saveIndex;

        for(int i = 0; i < [playerArray count]; i++) {
              player = nil;
              player = [playerArray objectAtIndex:i];
              if(player == nil)
                     break;
              name = player.playerName;// This “Player1″ denotes the player name could also be the computer name
              innerDict = [self getAllNodeInfoToDictionary:player];
              [rootObj setObject:innerDict forKey:name]; // This “Player1″ denotes the person who start this game
        }
        player = nil;
        NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:(id)rootObj format:NSPropertyListXMLFormat_v1_0 errorDescription:&errorDesc];
最後の2行は無視できます。少しだけrootObjの内容を追加します。このplistDataは作成したplistファイルのために、そのwriteToFile方法でファイルを作成することができます。以下はコードです
/*              */
        NSString *documentsPath = [self getDocumentsDirectory];
        NSString *savePath = [documentsPath stringByAppendingPathComponent:@"save.plist"];

        /*   */
        if (plistData) {
                [plistData writeToFile:savePath atomically:YES];
         }
         else {
                NSLog(errorDesc);
                [errorDesc release];
        }

        - (NSString *)getDocumentsDirectory {
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                return [paths objectAtIndex:0];
        }
plistファイルを読み込み、NSDictionaryに変換します。
        NSString *documentsPath = [self getDocumentsDirectory];
        NSString *fullPath = [documentsPath stringByAppendingPathComponent:@"save.plist"];
        NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];
一般文書ファイルを読み込む
        NSString *tmp;
        NSArray *lines; /*           */
        lines = [[NSString    stringWithContentsOfFile:@"testFileReadLines.txt"]
                       componentsSeparatedByString:@”
”]; NSEnumerator *nse = [lines objectEnumerator]; // <> while(tmp = [nse nextObject]) { NSString *stringBetweenBrackets = nil; NSScanner *scanner = [NSScanner scannerWithString:tmp]; [scanner scanUpToString:@"<" intoString:nil]; [scanner scanString:@"<" intoString:nil]; [scanner scanUpToString:@">" intoString:&stringBetweenBrackets]; NSLog([stringBetweenBrackets description]); }
読み书きについては、まだ补充があります。乱数やファイル読み书きはゲーム开発でよく使われます。だから、一部の内容をここに置いて、みんなと共有するために、記録として、探しやすいです。
ナショナルバーを隠す
[self.navigationController setNavigationBarHidden:YES animated:YES];
隠したいView Controllerの中で使えばいいです。
子の行動の整合性が保証されない場合は、委託でお願いします。
If the subClass cann’t keep with super Class,use delegate rather than inherityance.
スクリーンで見たのは全部UVewです。
Everything you see on Sreen is Uview.
性能に対する要求が高いなら、Interface Buildを慎みます。
ifアプリ’s performance is import,be discreet for the interface build.
copyは作成で、retainは参照です。
the copy operation is create a new one,but the retain operation is just a reference.
allocはreleaseが必要で、conventはreleaseを必要としません。
alloc method need coreress ponding release method、but convent method not.
NSAray/NSMutable Arayにロードされたオブジェクトは、releaseを担当する必要はありません。
The object added to NSAray/NSMutable Aray need not to be released.
IBOutletは、IBActionがInterface Buiildのオブジェクトを訪問するゲートを開けました。
IBOutlet and IBAction the door to access the object in Interface build.
UUAppliation Delegateはアプリケーションのライフサイクルを担当していますが、UID View ControllerはViewのライフサイクルを担当しています。
UApplication Delegate is reponsible for the applife cycle,but UID View Controller for the UID View.
プログラムの頑丈さのために、Delegateのライフサイクル関数をできるだけ実現してください。
if you want to develop a robust aplication、implement the life cycle methods as more as possbile.
タッチはUEventではなく、NSSetのUIViewです。
what you touch on screen is not UEvent but UID View
UITText Fieldはキーボードに応答しません。
    1: TextField  Touch Cancel   ,  [textFied resignFirstResponder];

        : - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

  [textFied resignFirstResponder]; }
応答キーボードreturnボタンを変更:
    TextField.returnKeyType=UIReturnKeyDone;
select:
   UIReturnKeyDefault,
   UIReturnKeyGo,
   UIReturnKeyGoogle,
   UIReturnKeyJoin,
   UIReturnKeyNext,
   UIReturnKeyRoute,
   UIReturnKeySearch,
   UIReturnKeySend,
   UIReturnKeyYahoo,
   UIReturnKeyDone,
   UIReturnKeyEmergencyCall,
サイズの問題:
   iPhone        :57*57;

   iPhone  UIView  :320*460   UITabBar   :320*411

   UITabelViewCell    : 320*44
コントロールの描画方法
//--alloc
-(UITextField *)GetDefaultTextField:(CGRect)frame{

    UITextField *textField=[[UITextField alloc] initWithFrame:frame];
    textField.borderStyle=UITextBorderStyleRoundedRect;
    textField.font=[UIFont fontWithName:@"Arial" size:12.0];
    textField.textAlignment=UITextAlignmentCenter;
    textField.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
    textField.keyboardType=UIKeyboardTypeNumbersAndPunctuation;
    textField.returnKeyType=UIReturnKeyDone;
    textField.delegate=self;
    return textField;

}
//--alloc
-(UILabel *)GetDefaultLabel:(CGRect)frame{

    UILabel *label = [[UILabel alloc] initWithFrame: frame];
    label.textAlignment=UITextAlignmentCenter;
    label.textColor=[UIColor blackColor];
    label.backgroundColor=[UIColor clearColor];
    label.font=[UIFont boldSystemFontOfSize:12.0];
    return label;
}
//--alloc
-(UIButton *)GetDefaultButton:(CGRect)frame{

    UIButton *button=[[UIButton alloc] initWithFrame:frame];
    [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [button.titleLabel setFont:[UIFont boldSystemFontOfSize:14.0]];
    [button.titleLabel setLineBreakMode:UILineBreakModeCharacterWrap];
    [button addTarget:self action:@selector(btnTradeTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];

                [button setBackgroundImage:[UIImage imageNamed:@"png1.png"] forState:UIControlStateNormal];
                [button setBackgroundColor:[UIColor lightGrayColor]];
                button.tag=kButtonTag;

     return button;}
マクロを使用して定数を定義します。タグの大きさを判断します。
#define kIndexValueTag 1
アップルスクリーンのショートカットキー
一般的にMacではCommand Shif-3/4で写真を撮ります。注:Command=アップルキーにはいくつかの補助キーがあります。他のスクリーンショット機能があります。
1)Command-Shift-3(   OS9,10.1X 10.2)
             。
2)Command-Shift-4(   OS9,10.1X 10.2)
               。        ,         ,           。
3)Command-Shift-Control-3(   OS9 10.2)
              ,  Command+V      Photoshop      。
4)Command-Shift-Control-4(   OS9 10.2)
                。
5)Command-Shift-4     (   10.2)
          ,             Dock     ,             (           )  。
6)Command-Shift-Control-4     (   10.2)
                    。
7)Command-Shift-Capslock-4(   OS9)
              。
8)Command-Shift-Capslock-Control-4(   OS9)
               。