iOS开发技术部落注意点iOS学习

iOS开发小冷易忘知识点总结

2016-08-31  本文已影响465人  Ke_Wang

整理一下一些偏冷知识点,偶尔看一下。各位道友如果发现什么错误请及时指正,有好的东西也可以往上面补充!

  - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    CGPoint hitPoint = [self.cardView.dayRateHelp convertPoint:point fromView:self];
    if ([self.cardView.dayRateHelp pointInside:hitPoint withEvent:event])
        return self.cardView.dayRateHelp;
    return [super hitTest:point withEvent:event];
}
  [self.pageControl setValue:currentImage forKey:@"_currentPageImage"];
  [self.pageControl setValue:pageImage forKey:@"_pageImage"];
-   数据发生改变后一定要重新刷新数据  
- (void)viewWillAppear:(BOOL)animated{  

    [super viewWillAppear:animated];  
    /** 
     *  clearsSelectionOnViewWillAppear 
     *  这个是它的一个属性,默认是yes 返回列表页面的时候,默认取消这行的选中状态,可是我们已经把这条数据删除的话,会出问题 
     *  如果你点击了一行cell,进入下一个页面,在这个页面中,我们把本该属于这行cell的数据给删了 
     *  如果  self.clearsSelectionOnViewWillAppear = yes,返回前一页时,会刷新这一行cell,执行cellForRow方法,结果数据却没了,就崩溃了 
     *  如果  self.clearsSelectionOnViewWillAppear = no,不会刷新这一行cell,就没事儿了 
     */  
   self.clearsSelectionOnViewWillAppear =NO;  
    [self.tableView reloadData];---->并不一定要放在这里,看取得数据在什么位置,刷新数据在什么位置  
}  
- (NSString *)transformMandarinToLatin:(NSString *)string  
{  
    NSMutableString *preString = [string mutableCopy];  
    /*转换成成带音 调的拼音*/  
    CFStringTransform((CFMutableStringRef)preString, NULL, kCFStringTransformMandarinLatin, NO);  
    /*去掉音调*/  
    CFStringTransform((CFMutableStringRef)preString, NULL, kCFStringTransformStripDiacritics, NO);  
    return preString;  
}  
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShown:)  
name:UIKeyboardWillShowNotification object:nil];  
   - (void)keyboardWillShown:(NSNotification *)aNotification{
  // 键盘信息字典
  NSDictionary *info = [aNotification userInfo];

}


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShown:)  

name:UIKeyboardWillShowNotification object:nil];  

- (void)keyboardWillShown:(NSNotification*)aNotification{  
    // 键盘信息字典  
    NSDictionary* info = [aNotification userInfo];  
}  

在Info.plist 添加

UIViewControllerBasedStatusBarAppearance, 设置值为 NO

然后再didFinishLaunchingWithOptions的AppDelegate, 添加这些代码:

[application setStatusBarHidden:NO];[application setStatusBarStyle:UIStatusBarStyleLightContent];

Xcode升级到5.1,apple默认让所有app都通过64位编译器编译。通过下面的方式可以关闭: 选中Targets—>Build Settings—>Architectures。双击Architectures,选择other,删除$(ARCH_STANDARD)(点’-’),然后增加armv7和armv7s(点‘+’)。clean一下再编译就行了。


#import <QuartzCore/QuartzCore.h>  

#define kNavBarDefaultPosition CGPointMake(160, 22)  

        if (contentOffsetY > _scrollViewContentOffsetYThreshold) {  

            layer.position = CGPointMake(layer.position.x,  

           - MIN((contentOffsetY - _scrollViewContentOffsetYThreshold), 48.0));  

        }  

        else  

        {  

            layer.position = kNavBarDefaultPosition;    

        }  


UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 120, 120, 120)];  

// 获取矩形左边缘的x坐标  

NSLog(@"MinX = %f",CGRectGetMinX(view.frame));  

// 获取矩形顶部的y坐标  

NSLog(@"MinY = %f",CGRectGetMinY(view.frame));  

// 获取矩形中心点的坐标  

NSLog(@"MidX = %f",CGRectGetMidX(view.frame));  

NSLog(@"MidY = %f",CGRectGetMidY(view.frame));  

// 获取矩形右边缘的x坐标  

NSLog(@"MaxX = %f",CGRectGetMaxX(view.frame));  

// 获取矩形底部的y坐标  

NSLog(@"MaxY = %f",CGRectGetMaxY(view.frame));  

// 返回手势在一个UIView上的触摸点坐标  

- (CGPoint)locationInView:(UIView *)view:  

// 判断矩形是否包含了一个点  

NSLog(@"isRectContainPoint = %d",CGRectContainsPoint(view.frame, CGPointMake(160, 180)));  


CGRectInset CGRect CGRectInset (    

CGRect rect,    

CGFloat dx,    

CGFloat dy    

);    

该结构体的应用是以原rect为中心,再参考dx,dy,进行缩放或者放大。    

CGRect r1 = CGRectMake(100, 100, 50, 50);    

CGRect r3 = CGRectInset(r1, 10, 8);//结果应为:110,108,30,34 具体小多少都是要参照dx和dy来判定的。    


CGRectOffset CGRect CGRectOffset(    

CGRect rect,    

CGFloat dx,    

CGFloat dy    

); 相对于源矩形原点rect(左上角的点)沿x轴和y轴偏移, 再rect基础上沿x轴和y轴偏移    

float offset = 125.0;    

CGRect r1 = CGRectMake(100, 100, 5, 5);    

CGRect r2 = CGRectOffset(r1, offset, offset);    

结果:    

 {{225, 225}, {5, 5}}    

// 将像素point由point所在视图转换到目标视图view中,返回在目标视图view中的像素值  

- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;  

// 将像素point从view中转换到当前视图中,返回在当前视图中的像素值  

- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;  

// 将rect由rect所在视图转换到目标视图view中,返回在目标视图view中的rect  

- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;  

// 将rect从view中转换到当前视图中,返回在当前视图中的rect  

- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;  

例把UITableViewCell中的subview(btn)的frame转换到 controllerA中  

// controllerA 中有一个UITableView, UITableView里有多行UITableVieCell,cell上放有一个button  

// 在controllerA中实现:  

CGRect rc = [cell convertRect:cell.btn.frame toView:self.view];  

或  

CGRect rc = [self.view convertRect:cell.btn.frame fromView:cell];  

// 此rc为btn在controllerA中的rect  

或当已知btn时:  

CGRect rc = [btn.superview convertRect:btn.frame toView:self.view];  

或  

CGRect rc = [self.view convertRect:btn.frame fromView:btn.superview];  

CGImage和CGImageRef这两个应当是用来重绘图形的类,它们在应用时是按照图像的像素矩阵来绘制图片的,它们可以用来处理bitmap。

CGImageRef与UIImage的互转

// CGImageRef转换成UIImage CGImageRef  

iOffscreen = CGBitmapContextCreateImage(context);

UIImage* image = [UIImage imageWithCGImage: iOffscreen];

// UIImage转换成CGImageRef  

UIImage *loadImage=[UIImage imageNamed:@"888.png"];

CGImageRef cgimage=loadImage.CGImage;
NSData *data;  

        if (UIImagePNGRepresentation(image) == nil) {  

            data = UIImageJPEGRepresentation(image, 1);  

        } else {  

            data = UIImagePNGRepresentation(image);  

        }  


 [fileManager createFileAtPath:[filePath stringByAppendingString:@"/image.png"] contents:data attributes:nil];    将图片保存为PNG格式  

 [fileManager createFileAtPath:[filePath stringByAppendingString:@"/image.jpg"] contents:data attributes:nil];   将图片保存为JPEG格式  

我们也可以写成下面的格式存储图片


NSString *pngImage = [filePath stringByAppendingPathComponent:@"Documents/image.png"];  

NSString *jpgImage = [filePath stringByAppendingPathComponent:@"Documents/image.jpg"];  

[data writeToFile:pngImage atomically:YES];  

[data writeToFile:jpgImage atomically:YES];  

button.titleLabel.font = [UIFont systemFontOfSize: 28.0];


CLLocation *orig=[[CLLocation alloc] initWithLatitude:[mainDelegate.latitude_self doubleValue]  longitude:[mainDelegate.longitude_self doubleValue]];    

CLLocation* dist=[[CLLocation alloc] initWithLatitude:[tmpNewsModel.latitude doubleValue] longitude:[tmpNewsModel.longitude doubleValue]];    

CLLocationDistance kilometers=[orig distanceFromLocation:dist]/1000;    

NSLog(@"距离:",kilometers);    

获得开发签名后在真机器上部署测试,在点击Build And Run后,提示The executable was signed with invalid entitlements.(The entitlements specified in your application’s Code Signing Entitlements file do not match those specified in your provisioning profile.)错误->(0xE8008016),
解决方法如下:

第一步:在工程中添加文件new file,选择Code Signing 中的Entitlements,添加后名称为Entitlements.plist。

第二步:点击Entitlements.plist进行编辑,删除所有Root下的Key,然后添加一个Boolean类型,名称为get-task-allow的Key,状态为CHECKED

第三步:在Targets中的Info中的Build选项卡中的Code Signing Entitlements的值设为Entitlements.plist,重新Build即可解决


+ (UIImage *)getFirstFrameOfVideoWithVideoURL:(NSURL *)videoURL  

{  

    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];  

    NSParameterAssert(asset);  

    AVAssetImageGenerator *assetIG = [[AVAssetImageGenerator alloc] initWithAsset:asset];  

    assetIG.appliesPreferredTrackTransform = YES;  

    assetIG.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;  

    CGImageRef thumbnailImageRef = NULL;  

    CFTimeInterval thumbnailImageTime = 60;  

    NSError *igError = nil;  

    thumbnailImageRef = [assetIG copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&igError];  

    if (!thumbnailImageRef)  

        NSLog(@"thumbnailImageGenerationError %@", igError );  

    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;  

    return thumbnailImage;  

}  


- (void)viewDidLayoutSubviews  

{      

    [super viewDidLayoutSubviews];  

    self.mScrollView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);  

    self.mScrollView.contentSize = CGSizeMake(kScreenWidth, 568);     

}  

- (void) viewDidAppear:(BOOL)animated  

{  

       self.scrollView.frame = CGRectMake(0, 0, 320, 480);  

       [self.scrollView setContentSize:CGSizeMake(320, 1000)];  

} 


+ (UIColor *)colorFromHexString:(NSString *)hexString  

{  

    if ([[hexString substringToIndex:1] isEqualToString:@"#"]) {  

        hexString = [hexString substringFromIndex:1];  

    }  

    unsigned rgbValue = 0;  

    NSScanner *scanner = [NSScanner scannerWithString:hexString];  

    [scanner scanHexInt:&rgbValue];  

    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];  

}  


+ (UIImage *)compressImage:(UIImage *)imgSrc withSize:(CGSize)size  

{  

    UIGraphicsBeginImageContext(size);  

    CGRect rect = {{0,0}, size};  

    [imgSrc drawInRect:rect];  

    UIImage *compressedImg = UIGraphicsGetImageFromCurrentImageContext();  

    UIGraphicsEndImageContext();  

    return compressedImg;  

}  

 frame(帧):一个gif可以简单认为是多张image组成的动画,一帧就是其中一张图片image.
 frameCount(帧数): 就是一个gif有多少帧
 loopCount(播放次数):有些gif播放到一定次数就停止了,如果为0就代表gif一直循环播放。
delayTime(延迟时间):每一帧播放的时间,也就是说这帧显示到delayTime就转到下一帧。
 所以gif播放主要就是把每一帧image解析出来,然后每一帧显示它对应的delaytime,然后再显示下一张。如此循环下去。
下面是纯粹实现由系统提供的解码:
-(void)decodeWithFilePath:(NSString *)filePath  
{  
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^() {  

        NSData *data = [NSData dataWithContentsOfFile:self.path];  

        [self decodeWithData:data];  
    });  
}  
        - (void)decodeWithData:(NSData *)data  
        {  
            CGImageSourceRef src = CGImageSourceCreateWithData((CFDataRef) data, NULL);  
            if (src)  
            {  
        //获取gif的帧数  
        NSUInteger frameCount = CGImageSourceGetCount(src);  
        //获取GfiImage的基本数据  
        NSDictionary *gifProperties = (NSDictionary *) CGImageSourceCopyProperties(src, NULL);  
        if(gifProperties)  
        {  
           //由GfiImage的基本数据获取gif数据  

            NSDictionary *gifDictionary =[gifProperties objectForKey:(NSString*)kCGImagePropertyGIFDictionary];  

            //获取gif的播放次数  

            NSUInteger loopCount = [[gifDictionary objectForKey:(NSString*)kCGImagePropertyGIFLoopCount] integerValue];  

            for (NSUInteger i = 0; i < frameCount; i++)  
            {  
                 //得到每一帧的CGImage  
                CGImageRef img = CGImageSourceCreateImageAtIndex(src, (size_t) i, NULL);  
                if (img)  
                {  
                    //把CGImage转化为UIImage  
                    UIImage *frameImage = [UIImage imageWithCGImage:img];  
                    //获取每一帧的图片信息  
                    NSDictionary *frameProperties = (NSDictionary *) CGImageSourceCopyPropertiesAtIndex(src, (size_t) i, NULL);  
                    if (frameProperties)  
                    {  
                        //由每一帧的图片信息获取gif信息  
                        NSDictionary *frameDictionary = [frameProperties objectForKey:(NSString*)kCGImagePropertyGIFDictionary];  
                        //取出每一帧的delaytime  
                        CGFloat delayTime = [[frameDictionary objectForKey:(NSString*)kCGImagePropertyGIFDelayTime] floatValue];  
                       //TODO 这里可以实现边解码边回调播放或者把每一帧image和delayTime存储起来  
                       CFRelease(frameProperties);  
                    }  
                    CGImageRelease(img);  
                }  
            }  
            CFRelease(gifProperties);  
        }  
        CFRelease(src);  
    }      
}  

可能你会发现这个类的父类是NSMutableSet。纳尼?不是说NSMutableSet是不可以储存重复对象的吗。其实NSCountedSet也是不能储存重复的对象的,查看Apple文档中对这个类的描述有这么一句:

Each distinct object inserted into an NSCountedSet object has a counter associated with it.

插入NSCountedSet对象的每个不同的对象都有一个与之相关的计数器

也就是说如果遇到重复对象的加入,这个对象的计数器就会+1。所以可以到这个类有个名叫


- (NSUInteger)countForObject:(id)object    的方法来统计重复对象的个数。  

NSArray *array = @[@1, @2, @2, @1];  

NSCountedSet *set = [[NSCountedSet alloc]initWithArray:array];  

[set enumerateObjectsUsingBlock:^(id obj, BOOLBOOL *stop) {  

    NSLog(@"%@ => %d", obj, [set countForObject:obj]);  

}];  


[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)  

                                                     forBarMetrics:UIBarMetricsDefault];  


UIGraphicsBeginImageContext(self.view.bounds.size);  

 [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];  

 UIImage *image= UIGraphicsGetImageFromCurrentImageContext();  

 UIGraphicsEndImageContext();  

 UIImageWriteToSavedPhotosAlbum(image, self, nil, nil); 

- (UIImage *)creatImageWithView:(UIView *)view rect:(CGRect)rect  

{  

    CGSize size = view.bounds.size;  

    UIGraphicsBeginImageContextWithOptions(size, NO, 0);  

    [view.layer renderInContext:UIGraphicsGetCurrentContext()];  

    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();  

    UIGraphicsEndImageContext();  

    CGImageRef viewImageRef = viewImage.CGImage;  

    CGImageRef imageRef = CGImageCreateWithImageInRect(viewImageRef, rect);  

    UIImage *image = [[UIImage alloc] initWithCGImage:imageRef];  

    CGImageRelease(imageRef);  

    return image;  

}  
  - (UIViewController*)viewController {
      for (UIView* next = [self superview]; next; next = next.superview) {
          UIResponder* nextResponder = [next nextResponder];
          if ([nextResponder isKindOfClass:[UINavigationController class]]) {
              return (UIViewController*)nextResponder;
          }
      }
      return nil;
  }  
  //获取导航控制器
  - (UINavigationController*)navigationController {
      for (UIView* next = [self superview]; next; next = next.superview) {
          UIResponder* nextResponder = [next nextResponder];
          if ([nextResponder isKindOfClass:[UINavigationController class]]) {
              return (UINavigationController*)nextResponder;
          }
      }
      return nil;
  }
上一篇 下一篇

猜你喜欢

热点阅读