关闭

iphone开发工具常用方法

3816人阅读 评论(0) 收藏 举报

退回输入键盘:

?
1
2
3
- (BOOL) textFieldShouldReturn:(id)textField{
    [textField  resignFirstResponder];
}

CGRect

?
1
2
3
4
5
6
CGRect frame = CGRectMake (origin.x, origin.y, size.width, size.height);矩形
NSStringFromCGRect(someCG) 把CGRect结构转变为格式化字符串;
CGRectFromString(aString) 由字符串恢复出矩形;
CGRectInset(aRect) 创建较小或较大的矩形(中心点相同),+较小  -较大
CGRectIntersectsRect(rect1, rect2) 判断两矩形是否交叉,是否重叠
CGRectZero 高度和宽度为零的/位于(0,0)的矩形常量

CGPoint & CGSize

?
1
CGPoint aPoint = CGPointMake(x, y);    CGSize aSize = CGSizeMake(width, height);

设置透明度

?
1
[myView setAlpha:value];   (0.0 < value < 1.0)

设置背景色

?
1
2
3
[myView setBackgroundColor:[UIColor redColor]];
   (blackColor;darkGrayColor;lightGrayColor;whiteColor;grayColor; redColor; greenColor; blueColor; cyanColor;yellowColor;magentaColor;
orangeColor;purpleColor;brownColor; clearColor; )

自定义颜色:

?
1
UIColor *newColor = [[UIColor alloc] initWithRed:(float) green:(float) blue:(float) alpha:(float)];      0.0~1.0

宽度和高度

?
1
768X1024     1024X768    状态栏高 20 像素高   导航栏 工具栏 44像素高

隐藏状态栏:

?
1
[[UIApplication shareApplication] setStatusBarHidden: YES animated:NO]

横屏:

?
1
2
3
[[UIApplication shareApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight].
orientation == UIInterfaceOrientationLandscapeLeft
window=[[UIWindow alloc] initWithFrame:[UIScreen mainScreen] bounds];全屏

自动适应父视图大小:

?
1
2
aView.autoresizingSubviews = YES;
aView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);

定义按钮

?
1
2
3
4
UIButton *scaleUpButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[scaleUpButton setTitle:@"放 大" forState:UIControlStateNormal];
scaleUpButton.frame = CGRectMake(40, 420, 100, 40);
[scaleUpButton addTarget:self action:@selector(scaleUp) forControlEvents:UIControlEventTouchUpInside];

设置视图背景图片

?
1
2
3
4
5
6
7
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;

活动表单 <UIActionSheetDelegate>

?
1
2
3
4
5
6
7
8
9
10
11
- (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];
}

警告视图 <UIAlertViewDelegate>

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (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];
     }
}

动画效果

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
-(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 <UITableViewDateSource>

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#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;
}

图像:如果设置图像,则它显示在文本的左侧

文本标签:这是单元的主要文本(UITableViewCellStyleDefault 只显示文本标签)

详细文本标签:这是单元的辅助文本,通常用作解释性说明或标签

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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;
}

随机数的使用

?
1
2
3
4
5
6
7
8
头文件的引用
#import <time.h>
#import <mach/mach_time.h>
 
srandom()的使用
srandom((unsigned)(mach_absolute_time() & 0xFFFFFFFF));
 
直接使用 random() 来调用随机数

在UIImageView 中旋转图像

?
1
2
3
float rotateAngle = M_PI;
CGAffineTransform transform =CGAffineTransformMakeRotation(rotateAngle);
imageView.transform = transform;

以上代码旋转imageView, 角度为rotateAngle, 方向可以自己测试哦!

在Quartz中如何设置旋转点

?
1
2
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg.png"]];
imageView.layer.anchorPoint = CGPointMake(0.5, 1.0);

这个是把旋转点设置为底部中间。记住是在QuartzCore.framework中才得到支持。

创建.plist文件并存储

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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方法就可以写成文件。下面是代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*得到移动设备上的文件存放位置*/
        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

?
1
2
3
NSString *documentsPath = [self getDocumentsDirectory];
NSString *fullPath = [documentsPath stringByAppendingPathComponent:@"save.plist"];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];

读取一般性文档文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
NSString *tmp;
NSArray *lines; /*将文件转化为一行一行的*/
lines = [[NSString    stringWithContentsOfFile:@"testFileReadLines.txt"]
               componentsSeparatedByString:@”\n”];
 
 NSEnumerator *nse = [lines objectEnumerator];