Iphone代码片段导航

1.给UITableViewController添加ToolBar。

 self.navigationController.toolbarHidden = NO; //默认是隐藏的。

//添加MessageToolBar ,messageToolBar是IBOutlet的一个ToolBar。

 self.toolbarItems =  [[[NSMutableArray alloc] initWithArray:self.messageToolBar.items] autorelease];

 self.navigationController.toolbar.barStyle = self.messageToolBar.barStyle; 

2.后台运行一个方法,如果该方法需要修改UI,为了防止出错,应在主线程里修改UI。

[self performSelectorInBackground:@selector(updateInfo)];

在UpdateInfo里如果要修改UI ,

[self performSelectorOnMainThread:@selector(updateUIMethod) withObject:nil waitUntilDone:NO];

同时注意,后台程序的方法应该放在NSAutoRelease pool里的,如下所示:

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
xxxx
[pool release];

3.在A类里动态的设定B类或者C类的方法。

[self.actionTarget performSelector:self.actionMethod withObject:parameter];

actionTarget   -> id类型的属性。设置B 类或者C类。

actionMethod -> Sel类型的属性。设置具体的方法名

parameter     -> 参数

4.设置Navigation的提示信息和进度条设置

   self.navigationItem.prompt : 提示信息
   self.navigationItem.titleView :存放ProgressBar等其它提示信息的View

   在进度条显示完了后,需要清空显示进度信息:

   self.navigationItem.prompt = nil;
   self.navigationItem.titleView = nil;

5.从资源文件xib里加载View的方法

 NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyView"
                                                         owner:self
                                                       options:nil];
MyView *view = [nib objectAtIndex:0];

6. UIAlterView 修改默认的Frame高度

在其委托里实现这个方法

- (void)willPresentAlertView:(UIAlertView *)alertView 

{

    alertView.frame = CGRectMake(5.f, 1.f, 100.f, 200.f);

}

参考:http://stackoverflow.com/questions/2763713/change-width-of-uialertview-in-ipad

 

 7.获取iphone屏幕大小

CGRect screenBounds = [ [ UIScreen mainScreen ] bounds ];
CGRect screenRect= [ [ UIScreen mainScreen ] applicationframe ]; 

8. 修改TableView的样式,让UITableView显示Windows的背景图片。

    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.opaque = NO;
    self.tableView.backgroundView = nil;

   如果要修改UITableCell的事情backgroundColor需要再 tableView:willDisplayCell:forRowAtIndexPath:里修改。

9.通过图片获取颜色。 

[UIColor colorWithPatternImage:[UIImage imageNamed:@"imageName"]];

修改分割线颜色

 self.tableView.separatorColor = [UIColor blackColor]; 

显示文本的地方设置透明色 

 cell.textLabel.opaque = NO;

 这样整个cell就有立体感。 

10.设置UITableView 的checkmark显示样式

修改cell的 accessoryView 

 cell.accessoryView = UIImageView

11. 修改TableView距离导航缆的高度。 

 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

{
    return 10.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [[[UIView alloc] initWithFrame:CGRectZero] autorelease];;
}

12. 自定义TableViewCell的背景颜色和选择后的颜色。

 方法一:将TableViewCell的backgroundView和SelectBackGroundView修改成指定的View就可以了。

 方法二: 在Interface Builder里设置cell的image和SelectImage属性,但是要记得UItableView修改seperator的属性为None

13 颜色定义。

  美工一般定义好颜色,然后让程序员去填充颜色,美工一般给的是RGB颜色,那么RGB颜色如果换成UIColor

[UIColor colorWithRed:31.0/255 green:204.0/255 blue:39.0/255 alpha:1.0];

Red,Green,Blue只接受0-1的参数,换算方法是除以255。 

14. Xcode 4设置  NSZombieEnabled

 if you click on the scheme drop down bar -> edit scheme -> arguments tab and then add NSZombieEnabled in the Environment Variables column and YES in the value column

15.自动生成多语言化的StringTable

   如果在代码里全部是通过 NSLocalizedString(@"中文", nil)来对应多语言,最后要整理一个list,手动一个一个粘贴太麻烦。

  自动化生成方法:在命令行目录下进入项目根目录:执行 genstrings -a $(find . -name "*.m"),就会自动生成一个文件对应。

  参考网址 http://steelwheels.sourceforge.jp/Documents/genstring.html

http://iphone.longearth.net/2009/05/25/%E3%80%90iphone%E3%80%91localizablestrings%E3%82%92%E8%87%AA%E5%8B%95%E3%81%A7%E4%BD%9C%E3%82%8B-genstrings/ 

16.自定义bond字体 

[UIFont fontWithName:@"Helvetica-Bold" size:16.0] 

17  无边框透明UITableViewCell

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;   

self.tableView.separatorColor = [UIColor clearColor];              

self.tableView.backgroundColor = [UIColor clearColor];   

self.tableView.opaque = NO;   

self.tableView.backgroundView = nil;

--Cell修改--

self.backgroundView = [[[UIView alloc] init] autorelease];       

self.backgroundView.backgroundColor = [UIColor clearColor];       

self.selectedBackgroundView = [[[UIView alloc] init] autorelease];       

self.selectedBackgroundView.backgroundColor = [UIColor clearColor];

18. 隐藏Tabbar

SampleViewController *obj = [[SampleViewController alloc] init];

[obj setHidesBottomBarWhenPushed:YES];

[self.navigationController pushViewController:obj animated:YES];

[obj release];
19.从UIView获取UImage


  
  
#import QuartzCore/QuartzCore.h

- (UIImage *)getImageFromView:(UIView *)orgView  

{ UIGraphicsBeginImageContext(orgView.bounds.size);  

[orgView.layer renderInContext:UIGraphicsGetCurrentContext()];  

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();  

UIGraphicsEndImageContext();  

return image;  

20. 添加手式识别后,会屏蔽掉touchend方法

 

21.获取手机号码,和IMEI  

 

获取本地iphone手机号码

[[NSUserDefaults standardUserDefaults] valueForKey:@"SBFormattedPhoneNumber"];  

获取手机的imei

#import "Message/NetworkController.h" 

NetworkController *ntc=[[NetworkController sharedInstance] autorelease];  

NSString *imeistring = [ntc IMEI];  

imeistring就是获取的imei。 IMEI(International Mobile Equipment Identity)是国际移动设备身份码的缩写,国际移动装备辨识码,是由15位数字组成的"电子串号",它与每台手机一一对应,而且该码是全世界唯一的。

22 NLog的格式,经常忘记,做个笔记

%@ 对象
%d, %i 整数
%u   无符整形
%f 浮点/双字
%x, %X 二进制整数
%o 八进制整数
%zu size_t
%p 指针
%e   浮点/双字 (科学计算)
%g   浮点/双字
%s C 字符串
%.*s Pascal字符串
%c 字符
%C unichar
%lld 64位长整数(long long)
%llu   无符64位长整数
%Lf 64位双字
 


1.

如果您想在应用里添加提示功能,比如让 iPhone 机身震动,可以使用下面这行代码:
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); 

 

2.

UItextView设置圆角 

#import <QuartzCore/QuartzCore.h>


layer

UITextView.layer.cornerRadius = 6;

UITextView.layer.masksToBounds = YES;

角度可以自己调

 3.viewdidunload在内存发生警告的时候,会调用,当调回来的时候,就会继续执行viewdidload方法。 

 

4.iphone  set table scroll postion

    [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
[tableView reloadData];



UItableView  UITextField 

  

NSString *text = ((UITextField *)cell.accessoryView).text;

However, you must be careful about setting up cells and accessing their values. If any cell goes offscreen, it will be removed and you will not be able to access the text field. What you want to do when setting up your cell is:

cell.accessoryView = nil; //Make sure any old accessory view isn't there.

if (/*cell needs text field*/) {

    UITextField *textField = [[[UITextField alloc] initWithFrame:frame] autorelease];

    textField.text = savedValue;

    cell.accessoryView = textField;

    [textField addTarget:self action:@selector(textChanged:) forControlEvents:UIControlEventValueChanged];

}



...



- (void) textChanged:(UITextField *)source {

    self.savedValue = source.text;

}
从网上下载图片
id path = @"http://merrimusings.mu.nu/archives/images/groundhog2.jpg";
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data cache:NO]; 

 

NSURL *myURL = [[NSURL alloc] initWithString:@"http://www.google.com/intl/en_ALL/images/logo.gif"];

UIImage *myImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:myURL]];

CGSize imageSize = myImage.size;

UIImageView *myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(((320-imageSize.width)/2), ((480-imageSize.height)/2), imageSize.width, imageSize.height)];

myImageView.image = myImage;

[self.view addSubview:myImageView];

[myURL release];
[myImageView release];

[myImage release]; 

 

变例控件的subviews,如表格的cell的所有view找倒textfield

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {


[tableView deselectRowAtIndexPath:indexPath animated:YES];

UITableViewCell * cell= [tableView cellForRowAtIndexPath:indexPath];

UITextField *textField =nil;

for(UIView *subview in cell.subviews)

{

if([subview isMemberOfClass:[UITextField class]] )

{

textField = (UITextField *)subview;

[textField becomeFirstResponder];

}

}

//[tableView deselectRowAtIndexPath:indexPath animated:YES];

} 

 

 程序登录和退出时,如果要做自动登录,那么就有必要保存用户的登陆信息,可放在NSUserDefault里,如何使用它,下面有个Sample

Saving

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];

// saving an NSInteger
[prefs setInteger:42 forKey:@"integerKey"];

// saving a Double
[prefs setDouble:3.1415 forKey:@"doubleKey"];

// saving a Float
[prefs setFloat:1.2345678 forKey:@"floatKey"];

// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];

Retrieving

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// getting an NSString
NSString *myString = [prefs stringForKey:@"
keyToLookupString"];

// getting an NSInteger
NSInteger myInt = [prefs integerForKey:@"
integerKey"];

// getting an Float

float myFloat = [prefs floatForKey:@"floatKey"];

 

如何自动获取tableView每行的高度。

因为TableView的高度计算是先于TableCell的生成。所以必须先计算。参考网址http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/

代码
#define  FONT_SIZE 14.0f
#define  CELL_CONTENT_WIDTH 320.0f
#define  CELL_CONTENT_MARGIN 10.0f    

-  (CGFloat)tableView:(UITableView  * )tableView heightForRowAtIndexPath:(NSIndexPath  * )indexPath;
{
  NSString 
* text  =  [items objectAtIndex:[indexPath row]];
 
  CGSize constraint 
=  CGSizeMake(CELL_CONTENT_WIDTH  -  (CELL_CONTENT_MARGIN  *   2 ),  20000.0f );
 
  CGSize size 
=  [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
 
  CGFloat height 
=  MAX(size.height,  44.0f );
 
  
return  height  +  (CELL_CONTENT_MARGIN  *   2 );
}


-  (UITableViewCell  * )tableView:(UITableView  * )tv cellForRowAtIndexPath:(NSIndexPath  * )indexPath
{
  UITableViewCell 
* cell;
  UILabel 
* label  =  nil;
 
  cell 
=  [tv dequeueReusableCellWithIdentifier: @" Cell " ];
  
if  (cell  ==  nil)
  {
    cell 
=  [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier: @" Cell " ] autorelease];
 
    label 
=  [[UILabel alloc] initWithFrame:CGRectZero];
    [label setLineBreakMode:UILineBreakModeWordWrap];
    [label setMinimumFontSize:FONT_SIZE];
    [label setNumberOfLines:
0 ];
    [label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
    [label setTag:
1 ];
 
    [[label layer] setBorderWidth:
2.0f ];
 
    [[cell contentView] addSubview:label];
 
  }
  NSString 
* text  =  [items objectAtIndex:[indexPath row]];
 
  CGSize constraint 
=  CGSizeMake(CELL_CONTENT_WIDTH  -  (CELL_CONTENT_MARGIN  *   2 ),  20000.0f );
 
  CGSize size 
=  [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
 
  
if  ( ! label)
    label 
=  (UILabel * )[cell viewWithTag: 1 ];
 
  [label setText:text];
  [label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH 
-  (CELL_CONTENT_MARGIN  *   2 ), MAX(size.height,  44.0f ))];
 
  
return  cell;
}


 SNDate reference

http://iphonedevelopertips.com/cocoa/date-formatter-examples.html 

http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/DataFormatting/Articles/df100103.html

http://www.cocoachina.com/bbs/simple/?t10151.html 

 http://www.iphonedevsdk.com/forum/iphone-sdk-development/4528-help-nsdateformatter.html 

 EEE MMM d HH:mm:ss z yyyy"


Tue Apr 06 00:00:00 +0800 2010


NSString *createTime=@"Tue Apr 06 00:00:00 +0800 2010 ";

NSDateFormatter *dateFormat = [[NSDateFormatter allocinit];

[dateFormat setDateFormat:@"EEE MMM d HH:mm:ss z yyyy"];

NSDate *createDate = [dateFormat dateFromString: createTime];

 

UIToolBar add button and add space between two UIButtonItem

UIToolbar* toolbar = [[UIToolbar alloc]

  initWithFrame:CGRectMake(00, width, 45)];

[toolbar setBarStyleUIBarStyleDefault];

// create an array for the buttons

NSMutableArray* buttons = [[NSMutableArray allocinitWithCapacity:1];

UIBarButtonItem *backButton = [[UIBarButtonItem allocinitWithTitle:@"返回" style:UIBarButtonItemStyleBorderedtarget:self action:@selector(backPress:)];

UIBarButtonItem *flexItem = [[UIBarButtonItem allocinitWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace

  target:nil

  action:nil];

UIBarButtonItem *doneButton = [[UIBarButtonItem allocinitWithTitle:@"确定" style:UIBarButtonItemStyleBorderedtarget:self action:@selector(donePress:)];

[buttons addObject: backButton];

[buttons addObject: flexItem];

[flexItem release];

[buttons addObject: doneButton];

[backButton release];

[doneButton release];

[toolbar setItems:buttons animated:NO];

    [self.view addSubview:toolbar];

[toolbar release]; 

 推迟某个方法的执行

[self performSelector:@selector(loadDataFromNet) withObject:nil afterDelay:0.1]; 

 

通过Animate的方式移动View

         
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:kAnimationDurationStart];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [view setFrame:CGRectMake(0, [UIApplication sharedApplication].statusBarFrame.size.height, view.frame.size.width, view.frame.size.height)];
        [UIView commitAnimations];


 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值