ios開發常用技巧彙總 + 小功能代碼

一.

1. iOS 9 以後 使用http請求 所需的配置

在Info.plist中add Row添加NSAppTransportSecurity類型Dictionary。
在NSAppTransportSecurity下添加NSAllowsArbitraryLoads類型Boolean,值設爲YES

這裏寫圖片描述







二.

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:[NSData dataWithContentsOfURL: [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]] encoding:NSUTF8StringEncoding];
}

3.讀取⺴絡圖⽚

-(UIImage *)getImageByURL:(NSString *)url {
return [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding: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 %@",[currentLocale objectForKey:NSLocaleLanguageCode]);
NSLog(@"Country Code is %@",[currentLocale objectForKey:NSLocaleCountryCode]);

6.view之間轉換的動態效果設置

SecondViewController *secondViewController = [[SecondViewController alloc] init];
secondViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;//⽔水平翻轉
[self.navigationController presentModalViewController:secondViewController animated: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 = [paths stringByAppendingPathComponent:@"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 = [thePath stringByAppendingPathComponent:@"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];

13. 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; }

14.iPhone iPad中橫屏顯示代碼

1、強制橫屏

[application setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];

15.在infolist⾥裏⾯面加了Supported interface orientations這⼀一項,增加之後添加四個item就是 ipad的四個⽅方向

item0 UIInterfaceOrientationLandscapeLeft item1
UIInterfaceOrientationLandscapeRight

這表明只⽀支持橫屏顯⽰示 經常讓人混淆迷惑的問題 - 數組和其他集合類

16.當一個對象被添加到一個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它,以保證retain count的平衡。因爲將number加入數組的時候,已經retain它了,所以數組中的number變量不會被release

17. UIView動畫停止調用方法遇到的問題

在實現UIView的動畫的時候,並且使⽤用UIView來重複調⽤用它結束的回調時候要 注意以下⽅方法中的finished參數

-(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
if([finishied boolValue] == YES)
//一定要判斷這句話,要不在程序中當多個View刷新的時候,就可能出現動畫異常的現象 {
//執行想要的動作 }
}

18.判斷在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 pushed onto the
stack
NSLog(@"New view controller was pushed");
} else if ([viewControllers indexOfObject:self] == NSNotFound) { // View is disappearing because it was popped from the stack NSLog(@"View controller was popped");
} }

19. 連接字符串小技巧

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

20. 隨文字大小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.window addSubview: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];

21. UILabel字體加粗

//加粗
lb.font = [UIFont fontWithName:@"Helvetica-Bold" size:20]; //加粗並且傾斜
lb.font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:20];

22. 爲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]; }

23. 實現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: nil afterDelay: 3.0];
}
- (void)delayHideBars { [self showBar];
}

24. 自定義UINavigationItem.rightBarButtonItem

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"remote",@"mouse",@"text",nil]];
[segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"home_a.png"] atIndex:0 animated:YES];
[segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"myletv_a.png"] atIndex:1 animated:YES];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; segmentedControl.frame = CGRectMake(0, 0, 200, 30);
[segmentedControl setMomentary:YES];
[segmentedControl addTarget:self action:@selector(segmentAction:)
forControlEvents:UIControlEventValueChanged];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
self.navigationItem.rightBarButtonItem = barButtonItem;
[segmentedControl release];

UINavigationController直接返回到根viewController

  [self.navigationController popToRootViewControllerAnimated:YES];

想要從第五層直接返回到第二層或第三層,用索引的形式

[self.navigationController popToViewController: [self.navigationController.viewControllers objectAtIndex: ([self.navigationController.viewControllers count] - 2)] animated:YES];

25. 鍵盤監聽事件

#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:self selector:@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:nil context: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]; }

26、 ios6.0強制橫屏的方法:

在appDelegate裏調用

if (!UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation])) {
        [[UIApplication sharedApplication]
setStatusBarOrientation:
UIInterfaceOrientationLandscapeRight animated:NO];

27.打電話

//打完後自動返回應用

 UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:@"tel:10086"];// 貌似tel:// 或者 tel: 都行
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    //記得添加到view上
    [self.view addSubview:callWebview];

//電話狀態監控 添加CoreTelePhone.frame 導入

#import <CoreTelephony/CTCall.h>
#import <CoreTelephony/CTCallCenter.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>

> 屬性

@property (nonatomic, strong) CTCallCenter *callCenter;
@property (nonatomic) BOOL callWasStarted;


- (instancetype)init
{
    self = [super init];

    if (self) {

        self.callCenter = [[CTCallCenter alloc] init];
        self.callWasStarted = NO;

        __weak __typeof__(self) weakSelf = self;

        [self.callCenter setCallEventHandler:^(CTCall *call) {

            if ([[call callState] isEqual:CTCallStateIncoming] ||
                [[call callState] isEqual:CTCallStateDialing]) {

                if (weakSelf.callWasStarted == NO) {

                    weakSelf.callWasStarted = YES;

                    NSLog(@"Call was started.");
                }

            } else if ([[call callState] isEqual:CTCallStateDisconnected]) {

                if (weakSelf.callWasStarted == YES)
                {
                    weakSelf.callWasStarted = NO;


                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"" delegate:nil cancelButtonTitle:@"確認" otherButtonTitles:nil, nil];
                    [alert show];
                    NSLog(@"Call was ended.");
                }
            }
        }];
    }

    return self;
}

28. 獲取項目中的文件路徑

//視頻文件路徑,此視頻已經存入項目包中.屬於本地播放
    NSString *path  = [[NSBundle mainBundle] pathForResource:@"movie" ofType:@"mp4"];
    if (path) {
        NSLog(@"已檢測到所需要文件");
    }
    else{
        NSLog(@"文件不存在");
    }
    //生成一個視頻URL
    NSURL *url = [NSURL fileURLWithPath:path];
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章