ios开发常用技巧汇总

来源:互联网 发布:linux中如何测试网速 编辑:程序博客网 时间:2024/06/05 01:52
1、NSCalendar用法
-(NSString *) getWeek:(NSDate *)d
{
NSCalendar *calendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit |
NSDayCalendarUnit | NSWeekCalendarUnit;
NSDateComponents *components = [calendar components:units
fromDate:d];
[calendar release];
switch ([components weekday]) {
case1:
return @"Monday"; break;
case2:
return @"Tuesday"; break;
case3:
return @"Wednesday"; break;
case4:
return @"Thursday"; break;
case5:
return @"Friday"; break;
case6:
return @"Saturday"; break;
case7:
return @"Sunday"; break;
default:
return @"NO Week"; break;
}
NSLog(@"%@",components);
}
 
2、将网络数据读取为字符串
-(NSString *)getDataByURL:(NSString *)url {
return [[NSString alloc] initWithData:[NSDatadataWithContentsOfURL: [NSURL URLWithString:[urlstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]encoding:NSUTF8StringEncoding];
}
 
3、读取⺴络图⽚
-(UIImage *)getImageByURL:(NSString *)url {
return [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[urlstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
}
 
4、多线程(这种方式,只管建立线程,不管回收线程)
[NSThread detachNewThreadSelector:@selector(scheduleTask)toTarget:self withObject:nil];
-(void)scheduleTask
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[pool release];
}
 
如果有参数,则这么⽤
[NSThread detachNewThreadSelector:@selector(scheduleTask:)toTarget:self withObject:[NSDate date]];
-(void)scheduleTask:(NSDate *)mdate
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[pool release]; }
 
在线程⾥运⾏主线程⾥的⽅法
[self performSelectorOnMainThread:@selector(moveToMain)withObject:nil waitUntilDone:FALSE];
 
5、⽤户缺省值NSUserDefaults读取:
NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
NSArray *languages = [df objectForKey:@"AppleLanguages"];
NSLog(@"all language is %@",languages);
NSLog(@"index is %@",[languages objectAtIndex:0]);
NSLocale *currentLocale = [NSLocale currentLocale];
NSLog(@"language Code is %@",[currentLocaleobjectForKey:NSLocaleLanguageCode]);
NSLog(@"Country Code is %@",[currentLocaleobjectForKey:NSLocaleCountryCode]);
 
6、view之间转换的动态效果设置
SecondViewController *secondViewController = [[SecondViewControlleralloc] init];
secondViewController.modalTransitionStyle =UIModalTransitionStyleFlipHorizontal;//⽔水平翻转
[self.navigationControllerpresentModalViewController:secondViewControlleranimated:YES];
[secondViewController release];
 
 
7、UIScrollView 滑动用法: -(void)scrollViewDidScroll:(UIScrollView*)scrollView
{
NSLog(@"正在滑动中。。")
}
//⽤户直接滑动UIScrollView,可以看到滑动条
-(void)scrollViewDidEndDelerating:(UIScrollView *)scrollView{
}
//通过其他控件触发UIScrollView滑动,看不到滑动条
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView*)scrollView {
}
//UIScrollView 设置滑动不超出本⾝身范围
[scrollView setBounces:NO];
 
8、iphone的系统目录:
//得到Document:目录
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//得到temp临时目录
NSString *temPath = NSTemporaryDirectory();
//得到目录上的文件地址
NSString *address = [pathsstringByAppendingPathComponent:@"1.rtf"];
 
9、状态栏显⽰示indicator
[UIApplication sharedApplication].networkActivityIndicatorVisible =YES;
 
10、app Icon显示数字:
- (void)applicationDidEnterBackground:(UIApplication*)application
{
 
 [[UIApplication sharedApplication]setApplicationIconBadgeNumber:5];
}
11、sqlite保存地址:
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectoryNSUserDomainMask,YES);
NSString *thePath = [paths objectAtIndex:0];
NSString *filePath = [thePathstringByAppendingPathComponent:@"kilometer.sqlite"];
NSString *dbPath = [[[NSBundle mainBundle]resourcePathstringByAppendingPathComponent:@"kilometer2.sqlite"];
 
12、键盘弹出隐藏,textfield变位置
_tspasswordTF = [[UITextField alloc] initWithFrame:CGRectMake(100,
150, 260, 30)];
_tspasswordTF.backgroundColor = [UIColor redColor];
_tspasswordTF.tag = 2;

//添加边框
CALayer*layer = [self.pageContenter layer];
layer.borderColor= [[UIColorwhiteColor]CGColor];
layer.borderWidth=0.0f;
//添加四个边阴影
self.pageContenter.layer.shadowColor=[UIColorblackColor].CGColor;//阴影颜色
self.pageContenter.layer.shadowOffset=CGSizeMake(0,0);//阴影偏移self.pageContenter.layer.shadowOpacity=0.5;//阴影不透明度self.pageContenter.layer.shadowRadius=5.0;//阴影半径
⼆二、给视图加上阴影
UIView * content=[[UIView alloc] initWithFrame:CGRectMake(100, 250,503, 500)];
content.backgroundColor=[UIColor orangeColor];
//content.layer.shadowOffset=10;
content.layer.shadowOffset = CGSizeMake(5, 3);content.layer.shadowOpacity = 0.6; content.layer.shadowColor =[UIColor blackColor].CGColor;
[self.window addSubview:content];
 
76、UIView有一个属性,clipsTobounds 默认情况下是NO,如果,我们想要view2把超出的那部份隐藏起来的话,就得改变它的父视图也 就view1的clipsTobounds属性值。
view1.clipsTobounds = YES;
使用objective-c 建立UUID UUID是128位的值,它可以保证唯一性。通常,它是由机器本身网卡的MAC地
址和当前系统时间来生成的。 UUID是由中划线连接而成的字符串。例如:0A326293-BCDD-4788-8F2D-
C4D8E53C108B
在声明文件中声明一个方法:
#import
@interface UUIDViewController : UIViewController { }
- (NSString *) createUUID;
@end
对应的实现文件中实现该方法:
- (NSString *) createUUID {
CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);
NSString *uuidStr = (NSString*)CFUUIDCreateString(kCFAllocatorDefault, uuidObject);
CFRelease(uuidObject);
return uuidStr; }
 
77、iPhone iPad中横屏显示代码
1、强制横屏
[applicationsetStatusBarOrientation:UIInterfaceOrientationLandscapeRightanimated:NO];
2、在infolist⾥里⾯面加了Supported interfaceorientations这⼀一项,增加之后添加四个item就是 ipad的四个⽅方向
item0 UIInterfaceOrientationLandscapeLeft
item1 UIInterfaceOrientationLandscapeRight 这表明只⽀支持横屏显⽰示 经常让人混淆迷惑的问题- 数组和其他集合类
 
78、当一个对象被添加到一个array, dictionary, 或者 set等这样的集合类型中的时候,集合会retain它。 对应的,当集合类被release的时候,它会发送对应的release消息给包含在其中的对象。 因此,如果你想建立一个包含一堆number的数组,你可以像下面示例中的几个方法来做
NSMutableArray *array; int i;
// ...
for (i = 0; i < 10; i++) {
NSNumber *n = [NSNumber numberWithInt: i];
[array addObject: n]; }
在这种情况下, 我们不需要retain这些number,因为array将替我们这么做。 NSMutableArray*array;
int i;
// ...
for (i = 0; i < 10; i++) {
NSNumber *n = [[NSNumber alloc] initWithInt: i];
 [array addObject: n];
[n release];
}
在这个例子中,因为你使用了-alloc去建立了一个number,所以你必须显式的-release它,以保证retaincount的平衡。因为将number加入数组的时候,已经retain它了,所以数组中的number变量不会被release
 
79、UIView动画停止调用方法遇到的问题
在实现UIView的动画的时候,并且使⽤用UIView来重复调⽤用它结束的回调时候要注意以下⽅方法中的finished参数
-(void)animationDidStop:(NSString *)animationID finished:(NSNumber*)finished context:(void *)context
{
if([finishied boolValue] == YES)
//一定要判断这句话,要不在程序中当多个View刷新的时候,就可能出现动画异常的现象 {
//执行想要的动作 }
}
 
80、判断在UIViewController中,viewWillDisappear的时候是push还是 pop出来
- (void)viewWillDisappear:(BOOL)animated {
NSArray *viewControllers =self.navigationController.viewControllers; if(viewControllers.count > 1&& [viewControllers
objectAtIndex:viewControllers.count-2] == self) {
// View is disappearing because a new view controller was pushedonto the
stack
NSLog(@"New view controller was pushed");
} else if ([viewControllers indexOfObject:self] == NSNotFound) { //View is disappearing because it was popped from the stackNSLog(@"View controller was popped");
} }
 
81、连接字符串小技巧
NSString *string1 = @"abc / cde";
NSString *string2 = @"abc" @"cde";
NSString *string3 = @"abc" "cde";
NSLog( @"string1 is %@" , string1 );
NSLog( @"string2 is %@" , string2 ); NSLog( @"string3 is %@" ,string3 );
打印结果如下:
string1 is abc cde string2 is abccde
 
82、随文字大小label自适应
label=[[UILabel alloc] initWithFrame:CGRectMake(50, 23, 175,33)];
label.backgroundColor = [UIColor purpleColor];
[label setFont:[UIFont fontWithName:@"Helvetica" size:30.0]];
[label setNumberOfLines:0];
//[myLable setBackgroundColor:[UIColor clearColor]]; [self.windowaddSubview:label];
NSString *text = @"this is ok";
UIFont *font = [UIFont fontWithName:@"Helvetica" size:30.0];
CGSize size = [text sizeWithFont: font constrainedToSize:CGSizeMake(175.0f, 2000.0f) lineBreakMode:UILineBreakModeWordWrap];
CGRect rect= label.frame; rect.size = size;
[label setFrame: rect]; [label setText: text];
 
83、UILabel字体加粗
//加粗
lb.font = [UIFont fontWithName:@"Helvetica-Bold" size:20];//加粗并且倾斜
lb.font = [UIFont fontWithName:@"Helvetica-BoldOblique"size:20];
 
84、为IOS应用组件添加圆角的方法 具体的实现是使用QuartzCore库,下面我具体的描述一下实现过程:
• 首先创建一个项目,名字叫:ipad_webwiew
• 利⽤用Interface Builder添加⼀一个UIWebView,然后和相应的代码相关联 •添加QuartzCore.framework
代码实现: 头⽂文件:
#import
#import
@interface ipad_webwiewViewController : UIViewController {
IBOutlet UIWebView *myWebView; UIView *myView;
}
@property (nonatomic,retain) UIWebView *myWebView; @end
代码实现:
- (void)viewDidLoad {
[super viewDidLoad]; //给图层添加背景图⽚片: //myView.layer.contents =(id)[UIImage
imageNamed:@"view_BG.png"].CGImage; //将图层的边框设置为圆脚
myWebView.layer.cornerRadius = 8; myWebView.layer.masksToBounds =YES; //给图层添加⼀一个有⾊色边框
myWebView.layer.borderWidth = 5; myWebView.layer.borderColor =[[UIColor colorWithRed:0.52
green:0.09 blue:0.07 alpha:1] CGColor]; }
 
85、实现UIToolBar的自动消失
-(void)showBar
{
! [UIView beginAnimations:nil context:nil];
! [UIView setAnimationDuration:0.40];
! (_toolBar.alpha == 0.0) ? (_toolBar.alpha = 1.0) :(_toolBar.alpha = 0.0);
! [UIView commitAnimations];
}
- (void)viewDidAppear:(BOOL)animated {
[NSObject cancelPreviousPerformRequestsWithTarget: self];
[self performSelector: @selector(delayHideBars) withObject: nilafterDelay: 3.0];
}
- (void)delayHideBars { [self showBar];
}
 
86、自定义UINavigationItem.rightBarButtonItem
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithItems:[NSArrayarrayWithObjects:@"remote",@"mouse",@"text",nil]];
[segmentedControl insertSegmentWithImage:[UIImageimageNamed:@"home_a.png"] atIndex:0 animated:YES];
[segmentedControl insertSegmentWithImage:[UIImageimageNamed:@"myletv_a.png"] atIndex:1 animated:YES];
segmentedControl.segmentedControlStyle =UISegmentedControlStyleBar; segmentedControl.frame = CGRectMake(0,0, 200, 30);
[segmentedControl setMomentary:YES];
[segmentedControl addTarget:selfaction:@selector(segmentAction:)
forControlEvents:UIControlEventValueChanged];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]initWithCustomView:segmentedControl];
self.navigationItem.rightBarButtonItem = barButtonItem;
[segmentedControl release];
UINavigationController直接返回到根viewController
 [self.navigationControllerpopToRootViewControllerAnimated:YES];
想要从第五层直接返回到第二层或第三层,用索引的形式
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:([self.navigationController.viewControllers count] - 2)]animated:YES];
 
87、键盘监听事件
#ifdef __IPHONE_5_0
float version = [[[UIDevice currentDevice] systemVersion]floatValue];
if (version >= 5.0)
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)name:UIKeyboardWillChangeFrameNotification object:nil];
}
#endif
[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotification object:nil];
-(void)keyboardWillShow:(NSNotification *)notification {
NSValue *value = [[notification userInfo]objectForKey:@"UIKeyboardFrameEndUserInfoKey"];
CGRect keyboardRect = [value CGRectValue]; NSLog(@"value %@%f",value,keyboardRect.size.height); [UIView beginAnimations:nilcontext:nil];
[UIView setAnimationDuration:0.25];
keyboardHeight = keyboardRect.size.height; self.view.frame =CGRectMake(0, -(251 - (480 - 64 -
keyboardHeight)), self.view.frame.size.width,self.view.frame.size.height);
[UIView commitAnimations]; }
 
88、 ios6.0强制横屏的方法:
在appDelegate里调用
if (!UIDeviceOrientationIsLandscape([[UIDevice currentDevice]orientation])) {
       [[UIApplication sharedApplication]
setStatusBarOrientation:
UIInterfaceOrientationLandscapeRight animated:NO];
0 0
原创粉丝点击