ios开发常用技巧汇总 + 小功能代码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_19678579/article/details/53518574

一.

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];





1.修改导航栏的底线

通过图片来修改导航栏的黑色底线

-(void)viewWillAppear:(BOOL)animated{
//添加有一张有颜色的图片来改变底线的颜色
 [self.navigationController.navigationBar setShadowImage:nil];
    [self.navigationController.navigationBar setShadowImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"#D3DCE6"] andSize:CGSizeMake(SCREEN_WIDTH, 0.5)]];

}
-(void)viewWillDisappear:(BOOL)animated{
//添加有一张空白颜色的图片来去除底线
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];

}

猜你喜欢

转载自blog.csdn.net/qq_19678579/article/details/53518574
今日推荐