IOS实用代码片段 2

一、IOS使用Reachability实时检测网络连接状况

//在程序的启动处,开启通知
- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  //.....
 
//开启网络状况的监听
[[NSNotificationCenter defaultCenter] addObserver:self
       selector:@selector(reachabilityChanged:)
    name: kReachabilityChangedNotification
   object: nil];
hostReach =[[Reachability reachabilityWithHostName:@"www.google.com"] retain];//可以以多种形式初始化
[hostReach startNotifier]; //开始监听,会启动一个run loop
      [self updateInterfaceWithReachability: hostReach];
  //.....
}

// 连接改变
 
- (void)reachabilityChanged: (NSNotification*)note
{
Reachability*curReach = [note object];
NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
[self updateInterfaceWithReachability:curReach];
}

//处理连接改变后的情况
 
- (void)updateInterfaceWithReachability: (Reachability*)curReach
{
   //对连接改变做出响应的处理动作。
 
      NetworkStatus status=[curReach currentReachabilityStatus];
    
if (status== NotReachable) { //没有连接到网络就弹出提实况
UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"MyApp Name"
                         message:@"NotReachable"
                         delegate:nil
                         cancelButtonTitle:@"YES" otherButtonTitles:nil];
                         [alert show];
                         [alert release];
}

}


二、键盘通知,输入框随着键盘上下移动:

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _sendButton.hidden= YES;
    
    //给键盘注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(inputKeyboardWillChangeFrame:)
                                                 name:UIKeyboardWillChangeFrameNotification
                                               object:nil];
    
    defaultFrameY = self.commentView.frame.origin.y;
    NSLog(@"defaultFrameY %f",defaultFrameY);
}
-(void)inputKeyboardWillChangeFrame:(NSNotification *)notification
{
    CGFloat animationTime = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect keyBoardFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [UIView animateWithDuration:animationTime animations:^{
        
           self.commentView.frame = CGRectMake(0, keyBoardFrame.origin.y-40, 320, 40);
        [_MainView addSubview:_commentView];
        
    }];
}


三、图片的适应问题

//高清 但有裁剪
//        imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//        imageView.contentMode = UIViewContentModeScaleAspectFill;
//        imageView.clipsToBounds = YES;
        
        //没裁剪,没变形,但要求获取原图片的大小进行等比例缩放
        imageView.autoresizesSubviews = YES;
        imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        imageView.contentMode = UIViewContentModeScaleAspectFill;


四、iOS 获取本地视频的缩略图

+(UIImage *)getImage:(NSString *)videoURL
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:videoURL] options:nil];
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;    
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return thumb;

}
需要添加AVFoundation和CoreMedia.framework
另外一种那个方法
 
 
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoURL]; moviePlayer.shouldAutoplay = NO; 
UIImage *thumbnail = [moviePlayer thumbnailImageAtTime:time timeOption:MPMovieTimeOptionNearestKeyFrame];
//这个也一样

+(UIImage *)fFirstVideoFrame:(NSString *)path 
{ 
    MPMoviePlayerController *mp = [[MPMoviePlayerController alloc] 
                                   initWithContentURL:[NSURL fileURLWithPath:path]]; 
    UIImage *img = [mp thumbnailImageAtTime:0.0 
                                 timeOption:MPMovieTimeOptionNearestKeyFrame]; 
    [mp stop]; 
    [mp release]; 
    return img; 
}


五、 

iOS中定时器NSTimer使用

调用一次计时器方法:

[cpp]  view plain copy
  1. myTimer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(scrollTimer) userInfo:nil repeats:NO];  
  2. //不重复,只调用一次。timer运行一次就会自动停止运行  

重复调用计时器方法:

[cpp]  view plain copy
  1. timer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(function:) userInfo:nil repeats:YES];  
  2. //每1秒运行一次function方法。  
注意:将计数器的repeats设置为YES的时候,self的引用计数会加1。因此可能会导致self(即viewController)不能release,所以,必须在viewWillAppear的时候,将计数器timer停止,否则可能会导致内存泄露。

停止timer的运行,但这个是永久的停止:

[cpp]  view plain copy
  1. //取消定时器  
  2. [timer invalidate];  


要想实现:先停止,然后再某种情况下再次开启运行timer,可以使用下面的方法:

首先关闭定时器不能使用上面的方法,应该使用下面的方法:

[cpp]  view plain copy
  1. //关闭定时器  
  2. [myTimer setFireDate:[NSDate distantFuture]];  

然后就可以使用下面的方法再此开启这个timer了:

[csharp]  view plain copy
  1. //开启定时器  
  2. [myTimer setFireDate:[NSDate distantPast]];  

例子:比如,在页面消失的时候关闭定时器,然后等页面再次打开的时候,又开启定时器。

(主要是为了防止它在后台运行,暂用CPU)可以使用下面的代码实现:

[cpp]  view plain copy
  1. //页面将要进入前台,开启定时器  
  2. -(void)viewWillAppear:(BOOL)animated  
  3. {  
  4.     //开启定时器  
  5.     [scrollView.myTimer setFireDate:[NSDate distantPast]];  
  6. }  
  7.   
  8. //页面消失,进入后台不显示该页面,关闭定时器  
  9. -(void)viewDidDisappear:(BOOL)animated  
  10. {  
  11.     //关闭定时器  
  12.     [scrollView.myTimer setFireDate:[NSDate distantFuture]];  
  13. }  

六、IOS8 设置TableView Separatorinset 分割线从边框顶端开始

在ios8上 [TableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];不起作用  
   
经过测试加入下面方法 在ios7 8上都可以正常工作  
  
-(void)viewDidLayoutSubviews  
{  
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {  
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];  
    }  
      
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {  
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];  
    }  
}  
  
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath  
{  
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {  
        [cell setSeparatorInset:UIEdgeInsetsZero];  
    }  
      
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {  
        [cell setLayoutMargins:UIEdgeInsetsZero];  
    }  
}


七、跳转到app下载网页、app store

//跳转到app store应用页面
//int appid=949785706;//手游视界appid
//NSString *urlStr = [NSString stringWithFormat:@"http://itunes.apple.com/us/app/id%d",appid];
//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
                
//跳转到网页应用页面
//http://www.ifeimo.com/product.html  http://www.ifeimo.com/apk/lpds/06-30.ipa
NSString *urlStr =[NSString stringWithFormat:@"http://www.ifeimo.com/apk/lpds/06-30.ipa"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];


八、iOS 在UILabel显示不同的字体和颜色(转)

在项目开发中,我们经常会遇到在这样一种情形:在一个UILabel 使用不同的颜色或不同的字体来体现字符串,在iOS 6 以后我们可以很轻松的实现这一点,官方的API 为我们提供了UILabel类的attributedText, 使用不同颜色和不同字体的字符串,我们可以使用NSAttributedText 和 NSMutableAttributedText 类来实现。

现实代码:

1
2
3
4
@interface  ViewController : UIViewController
@property  ( nonatomic , strong)  IBOutlet  UILabel *attrLabel;
- ( IBAction )next:( id )sender;
@end

 .m文件 在viewDidLoad方法中添加以下代码:

1
2
3
4
5
6
7
8
9
self .title = @ "For iOS 6 & later" ;
NSMutableAttributedString  *str = [[ NSMutableAttributedString  alloc] initWithString:@ "Using NSAttributed String" ];
[str addAttribute: NSForegroundColorAttributeName  value:[UIColor blueColor] range: NSMakeRange (0,5)];
[str addAttribute: NSForegroundColorAttributeName  value:[UIColor redColor] range: NSMakeRange (6,12)];
[str addAttribute: NSForegroundColorAttributeName  value:[UIColor greenColor] range: NSMakeRange (19,6)];
[str addAttribute: NSFontAttributeName  value:[UIFont fontWithName:@ "Arial-BoldItalicMT"  size:30.0] range: NSMakeRange (0, 5)];
[str addAttribute: NSFontAttributeName  value:[UIFont fontWithName:@ "HelveticaNeue-Bold"  size:30.0] range: NSMakeRange (6, 12)];
[str addAttribute: NSFontAttributeName  value:[UIFont fontWithName:@ "Courier-BoldOblique"  size:30.0] range: NSMakeRange (19, 6)];
attrLabel.attributedText = str;

 

效果图:

如果想在iOS6.0以前版本实现这个效果,需要使用到一个第三方库TTTAttributedLabel,同时还有导入CoreText.frame框架.


九、保存图片到相册

//保存到相册
- (void)saveImageToPhotos:(UIImage*)savedImage
{
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
// 指定回调方法
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存图片结果提示"
                                                    message:msg
                                                   delegate:self
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
    
}

十、如何删除UIWindow?

1. 不调用-resignKeyWindow直接,它被重写以执行代码时,你UIWindows被删除。为了消除旧的窗口中,您需要创建一个UIWindow的新实例,并使其-makeKeyAndVisible,旧的窗口将辞去其关键在iOS 4的甚至会垃圾回收你的旧UIWindow中,只要你没有给它任何引用。在iOS中3.x中这样做会有效果。警告你。 
2. 隐藏窗口的正确方法是设置hidden属性为YES。从的UIApplication的移除windows属性 CodeGo.net,您只要松开窗口(ARC您设置为nil的所有引用)。 当然,你会希望在这个拥有另一个窗口到位 
3. 删除它是这样的:
[myWindow resignKeyWindow];
[myWindow release];
释放使得它从窗户的UIApplication数组得到消除。您可以查看[[的UIApplication sharedApplication]。窗口数],以验证它是否已正确删除。 
4. 我有这个问题,它可能会有所帮助。 你需要摧毁所有强大的裁判删除之前的dealloc一个窗口,尤其是rootWindowController。我认为下面的代码,就足以删除任何窗口:
 [self.window.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
 self.window.rootViewController = nil;
 [self.window resignKeyWindow];
 [self.window removeFromSuperview];


math.h里的数学计算公式介绍   


       1、 三角函数 
  double sin (double);正弦 
  double cos (double);余弦 
  double tan (double);正切 
  2 、反三角函数 
  double asin (double); 结果介于[-PI/2, PI/2] 
  double acos (double); 结果介于[0, PI] 
  double atan (double); 反正切(主值), 结果介于[-PI/2, PI/2] 
  double atan2 (double, double); 反正切(整圆值), 结果介于[-PI, PI] 
  3 、双曲三角函数 
  double sinh (double); 
  double cosh (double); 
  double tanh (double); 
  4 、指数与对数 
  double exp (double);求取自然数e的幂 
  double sqrt (double);开平方 
  double log (double); 以e为底的对数 
  double log10 (double);以10为底的对数 
  double pow(double x, double y);计算以x为底数的y次幂 
  float powf(float x, float y); 功能与pow一致,只是输入与输出皆为浮点数 
  5 、取整 
  double ceil (double); 取上整 
  double floor (double); 取下整 
  6 、绝对值 
  double fabs (double);求绝对值 
  double cabs(struct complex znum) ;求复数的绝对值 
  7 、标准化浮点数 
  double frexp (double f, int *p); 标准化浮点数, f = x * 2^p, 已知f求x, p ( x介于[0.5, 1] ) 
  double ldexp (double x, int p); 与frexp相反, 已知x, p求f 
  8 、取整与取余 
  double modf (double, double*); 将参数的整数部分通过指针回传, 返回小数部分 
  double fmod (double, double); 返回两参数相除的余数 
  9 、其他 
  double hypot(double x, double y);已知直角三角形两个直角边长度,求斜边长度 
  double ldexp(double x, int exponent);计算x*(2的exponent次幂) 
  double poly(double x, int degree, double coeffs [] );计算多项式 
  nt matherr(struct exception *e);数学错误计算处理程序




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 20
    评论
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值