iOS开发小技巧

作者: 有草木青青 | 来源:发表于2017-01-11 16:52 被阅读170次

    1. 设置按钮字体居右

    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    
    2. 设置...显示的位置#######
    btn.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    
    //按钮图片与title位置显示设置
    CGRect imageRect = _lookPermissionButton.imageView.frame;
    CGRect titleRect = _lookPermissionButton.titleLabel.frame;
           
    titleRect.size.width = [_lookPermissionButton.titleLabel sizeThatFits:CGSizeMake(_lookPermissionButton.frame.size.width - imageRect.size.width, _lookPermissionButton.bounds.size.height)].width;
    
    _lookPermissionButton.imageEdgeInsets = UIEdgeInsetsMake(0, titleRect.size.width + 15 * kSACardWidthRatio(), 0, -titleRect.size.width - 15 * kSACardWidthRatio());
    
    _lookPermissionButton.titleEdgeInsets = UIEdgeInsetsMake(0, -imageRect.size.width, 0, imageRect.size.width);
    

    3. 添加虚线框 (只能用frame,masonry暂时实现不了)

    - (void)addLineDashToView:(UIView*)subview {
    
           CGFloatwidth = subview.frame.size.width;
    
           CGFloatheight = subview.frame.size.height;
    
           CAShapeLayer*shapelayer = [CAShapeLayerlayer];
    
           shapelayer.bounds=CGRectMake(0,0, width, height);
    
           shapelayer.position=CGPointMake(CGRectGetMidX(subview.bounds),CGRectGetMidY(subview.bounds));
    
           shapelayer.path= [UIBezierPathbezierPathWithRoundedRect:shapelayer.boundscornerRadius:5].CGPath;
    
           shapelayer.lineWidth=0.5;
    
           shapelayer.lineDashPattern=@[@5,@2];
    
           shapelayer.fillColor=nil;
    
           shapelayer.strokeColor=SAColorByRGB(200,200,200).CGColor;
    
           [subview.layeraddSublayer:shapelayer];
    
    }
    

    4. 单选

    - (void)ButtonAction:(UIButton*)btn {
    
           NSPredicate*pre = [NSPredicatepredicateWithFormat:@"SELF.isSelected == YES"];
    
           NSArray *selectArray = [_buttonArrayfilteredArrayUsingPredicate:pre];
    
           [selectArrayenumerateObjectsUsingBlock:^(UIButton*_Nonnullobj,NSUIntegeridx,BOOL*_Nonnullstop) {
    
               obj.selected=NO;
    
               obj.backgroundColor= [UIColorwhiteColor];
    
               obj.layer.borderColor=SAColorByRGB(235,235,235).CGColor;
    
           }];
    
           btn.selected=YES;
    
    }
    

    5. label字体自适应

    label.adjustsFontSizeToFitWidth = YES;
    

    6. 专业矢量图绘制工具
    地址 : http://xclient.info/s/paintcode.html?a=dl&v=&_=e979431218f41f8b93a2e8c2c788a9928780aa0d

    可根据绘制的图形,自动生成代码

    7. iOS开发中的权限检测与获取

    https://gold.xitu.io/entry/577c755dc4c9710066a7f553

    比如跳转到系统设置蓝牙:

    [[UIApplicationsharedApplication]openURL:[NSURLURLWithString:@"prefs:root=Bluetooth"]];

    其他的权限可以把下面字符串替换到上面

    About — prefs:root=General&path=About

    Accessibility — prefs:root=General&path=ACCESSIBILITY

    Airplane Mode On — prefs:root=AIRPLANE_MODE

    Auto-Lock — prefs:root=General&path=AUTOLOCK

    Brightness — prefs:root=Brightness

    Bluetooth — prefs:root=General&path=Bluetooth

    Date & Time — prefs:root=General&path=DATE_AND_TIME

    FaceTime — prefs:root=FACETIME

    General — prefs:root=General

    Keyboard — prefs:root=General&path=Keyboard

    iCloud — prefs:root=CASTLE

    iCloud Storage & Backup — prefs:root=CASTLE&path=STORAGE_AND_BACKUP

    International — prefs:root=General&path=INTERNATIONAL

    Location Services — prefs:root=LOCATION_SERVICES

    Music — prefs:root=MUSIC

    Music Equalizer — prefs:root=MUSIC&path=EQ

    Music Volume Limit — prefs:root=MUSIC&path=VolumeLimit

    Network — prefs:root=General&path=Network

    Nike + iPod — prefs:root=NIKE_PLUS_IPOD

    Notes — prefs:root=NOTES

    Notification — prefs:root=NOTIFICATIONS_ID

    Phone — prefs:root=Phone

    Photos — prefs:root=Photos

    Profile — prefs:root=General&path=ManagedConfigurationList

    Reset — prefs:root=General&path=Reset

    Safari — prefs:root=Safari

    Siri — prefs:root=General&path=Assistant

    Sounds — prefs:root=Sounds

    Software Update — prefs:root=General&path=SOFTWARE_UPDATE_LINK

    Store — prefs:root=STORE

    Twitter — prefs:root=TWITTER

    Usage — prefs:root=General&path=USAGE

    VPN — prefs:root=General&path=Network/VPN

    Wallpaper — prefs:root=Wallpaper

    Wi-Fi — prefs:root=WIFI

    8. OC 与Swift 语言互转 url地址:

    https://objectivec2swift.com/#/home/converter/

    9. NS_ASSUME_NONNULL_BEGIN && NS_ASSUME_NONNULL_END详解

    如果需要每个属性或每个方法都去指定nonnull和nullable,是一件非常繁琐的事。苹果为了减轻我们的工作量,专门提供了两个宏:NS_ASSUME_NONNULL_BEGIN和NS_ASSUME_NONNULL_END。

    Paste_Image.png

    10. 获取系统通讯录权限遇到的坑-01

    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted,CFErrorRef error) {
    
    });
    

    注意block块里的bool值一定不要写成大写的!!!

    注意block块里的bool值一定不要写成大写的!!!

    注意block块里的bool值一定不要写成大写的!!!

    11. 注册截屏通知

    [[NSNotificationCenterdefaultCenter]addObserver:self selector:@selector(userDidTakeScreenshot:) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    

    //截屏响应

    - (void)userDidTakeScreenshot:(NSNotification*)notification {
    
     [selfperformSelector:@selector(showNotification)withObject:nilafterDelay:0.5];
    
    }
    - (void)showNotification {
    
     [SANotificationViewshowNotificationViewWithContent:NSLocalizedString(@"已截屏,是要吐槽么?",nil)type:SANotificationViewTypeScreenShotsdidClick:nil];
    
    }
    

    12. 取消searchbar背景色

    - (UISearchBar*)searchBar{
    
    if(!_searchBar) {
    
       _searchBar= [[UISearchBaralloc]init];
    
       _searchBar.backgroundImage= [selfimageWithColor:[UIColorclearColor]size:CGSizeMake(4,4)];
    
       _searchBar.barStyle=UIBarStyleDefault;
    
       _searchBar.layer.cornerRadius=5;
    
       _searchBar.clipsToBounds=YES;
    
       _searchBar.backgroundColor=SAColorByRGB(243.0,243.0,243.0);
    
       _searchBar.placeholder=NSLocalizedString(@"搜索",nil);
    
       UITextField*field = [_searchBarvalueForKey:@"_searchField"];
    
       field.backgroundColor=SAColorByRGB(243.0,243.0,243.0);
    
       field.textColor=SAColorByRGB(51.0,51.0,51.0);
    
       field.font= [UIFontsystemFontOfSize:12];
    
       UIImage*image = [UIImageimageNamed:@"icon_search"];
    
       UIImageView*iconView = [[UIImageViewalloc]initWithImage:image];
    
       iconView.contentMode=UIViewContentModeCenter;
    
       iconView.frame=CGRectMake(0,0, image.size.width,28);
    
       field.leftView= iconView;
    
       [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(didChange:)name:UITextFieldTextDidChangeNotificationobject:nil];
    
    }
    
       return_searchBar;
    
    }
    
    
    - (UIImage*)imageWithColor:(UIColor*)color size:(CGSize)size {
    
       CGRectrect = CGRectMake(0,0, size.width, size.height);
    
       UIGraphicsBeginImageContext(rect.size);
    
       CGContextRefcontext = UIGraphicsGetCurrentContext();
    
       CGContextSetFillColorWithColor(context, [colorCGColor]);
    
       CGContextFillRect(context, rect);
    
       UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
       UIGraphicsEndImageContext();
    
       return image;
    
    }
    

    13. 正则判断
    13.1 判断手机号

    NSString *phoneRegex = @"(\\\\+\\\\d+)?1[34578]\\\\d{9}$";
    
    NSPredicate *phoneTest = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    
    return [phoneTestevaluateWithObject:string];
    

    13.2 判断邮箱

    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,4}";
    

    13.3 判断是否是纯数字

    NSString *emailRegex = @"^[0-9]*$";
    

    13.4 判断是否是全小写字母

    NSString *emailRegex = @"^[a-z]+$";
    

    13.5 判断是否全大写字母

    NSString *emailRegex = @"^[A-Z]+$";
    

    13.6 判断身份证号

    NSString *regex2 = @"^(\\\\d{14}|\\\\d{17})(\\\\d|[xX])$";
    

    13.7 判断含有中文字符

    for(inti =0; i < [stringlength]; i++){
    
       inta = [stringcharacterAtIndex:i];
    
    if( a >0x4e00&& a <0x9fff)
    
       returnYES;
    
    }
    
    returnNO;
    

    13.8 判断是否全是中文字符

    for(inti =0; i < [stringlength]; i++){
    
       inta = [stringcharacterAtIndex:i];
    
    if(a <0x4e00|| a >0x9fff) {
    
       returnNO;
    
     }
    
    }
    
    returnYES;
    

    13.9 只能是汉字和字母

    NSString *regex = @"^[a-zA-Z\\u4e00-\\u9fa5]+$";
    

    13.10 只能是数字和字母

    NSString *regex = @"^[0-9a-zA-Z]+$";
    

    13.11 只能是数字和汉字

    NSString *regex = @"[0-9\\u4e00-\\u9fa5]*";
    

    13.12 只能是数字、汉字和字母

    NSString *regex = @"[a-zA-Z0-9\\u4e00-\\u9fa5]*";
    

    14 CALayer 的震动 (一般写在CALayer的类别里)

    -(void)shake{
    
     CAKeyframeAnimation*kfa = [CAKeyframeAnimationanimationWithKeyPath:@"transform.translation.x"];
    
     CGFloats =16;
    
     kfa.values=@[@(-s),@(0),@(s),@(0),@(-s),@(0),@(s),@(0)];
    
     //时长
    
     kfa.duration=.1f;
    
     //重复
    
     kfa.repeatCount=2;
    
     //移除
    
     kfa.removedOnCompletion=YES;
    
     [selfaddAnimation:kfaforKey:@"shake"];
    
    }
    

    15. 对图片的一些操作 (一般写在类别里)
    15.1 改变图片透明度

    - (UIImage*)sa_imageWithAlpha:(CGFloat)alpha {
    
       if(alpha>1.0) {
    
         alpha =1.0;
    
       }
    
       if(alpha<=0.0) {
    
         alpha =0.0;
    
       }
    
       UIGraphicsBeginImageContextWithOptions(self.size,NO,0.0f);
    
       CGContextRefctx =UIGraphicsGetCurrentContext();
    
       CGRectarea =CGRectMake(0,0,self.size.width,self.size.height);
    
       CGContextScaleCTM(ctx,1, -1);
    
       CGContextTranslateCTM(ctx,0, -area.size.height);
    
       CGContextSetBlendMode(ctx,kCGBlendModeMultiply);
    
       CGContextSetAlpha(ctx, alpha);
    
       CGContextDrawImage(ctx, area,self.CGImage);
    
       UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
       UIGraphicsEndImageContext();
    
       returnnewImage;
    
    }
    

    15.2 任意改变图片尺寸

    - (UIImage*)sa_imageWithSize:(CGSize)size {
    
       UIGraphicsBeginImageContext(CGSizeMake(size.width, size.height));
    
       [selfdrawInRect:CGRectMake(0,0, size.width, size.height)];
    
       UIImage*resizedImage =UIGraphicsGetImageFromCurrentImageContext();
    
       UIGraphicsEndImageContext();
     
       returnresizedImage;
    
    }
    

    15.3 等比例放缩图片

    - (UIImage*)sa_imageStretchWithScale:(CGFloat)scale {
    
       UIGraphicsBeginImageContext(CGSizeMake(self.size.width* scale,self.size.height* scale));
    
       [selfdrawInRect:CGRectMake(0,0,self.size.width* scale,self.size.height* scale)];
    
       UIImage*scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    
       UIGraphicsEndImageContext();
    
       returnscaledImage;
    
    }
    

    15.4 图片压缩(返回NSData 压缩比例0.0~1.0)

    - (NSData*)sa_imageCompressReturnDataWithRatio:(CGFloat)ratio {
    
    //UIImageJPEGRepresentation和UIImagePNGRepresentation
    
       if(ratio>1.0) {
    
         ratio =1.0;
    
       }
    
      if(ratio<=0) {
    
       ratio =0.0;
    
       }
    
       NSData*compressedData =UIImageJPEGRepresentation(self, ratio);
    
       returncompressedData;
    
    }
    

    15.5 图片压缩 (返回UIImage 压缩比例0.0~1.0)

    - (UIImage*)sa_imageCompressReturnImageWithRatio:(CGFloat)ratio {
    
    //UIImageJPEGRepresentation和UIImagePNGRepresentation
    
       if(ratio>1.0) {
    
         ratio =1.0;
    
       }
    
       if(ratio<=0) {
    
         ratio =0.0;
    
       }
    
       NSData*compressedData =UIImageJPEGRepresentation(self, ratio);
    
       UIImage*compressedImage = [UIImageimageWithData:compressedData];
    
       returncompressedImage;
    
    }
    

    15.6 图片模糊 (模糊级别0.0 ~ 1.0)

    - (UIImage*)sa_imageBlurWithLevel:(CGFloat)level {
    
       if(level>1.0) {
    
         level =1.0;
    
       }
    
       if(level<=0) {
    
         level =0.0;
    
       }
    
       intboxSize = (int)(level *100);
    
       boxSize = boxSize - (boxSize %2) +1;
    
       CGImageRefimg = self.CGImage;
    
       vImage_BufferinBuffer, outBuffer;
    
       vImage_Errorerror;
    
       void *pixelBuffer;
    
       CGDataProviderRefinProvider =CGImageGetDataProvider(img);
    
       CFDataRefinBitmapData =CGDataProviderCopyData(inProvider);
    
       inBuffer.width=CGImageGetWidth(img);
    
       inBuffer.height=CGImageGetHeight(img);
    
       inBuffer.rowBytes=CGImageGetBytesPerRow(img);
    
       inBuffer.data= (void*)CFDataGetBytePtr(inBitmapData);
    
       pixelBuffer =malloc(CGImageGetBytesPerRow(img) *
    
       CGImageGetHeight(img));
    
       if(pixelBuffer ==NULL)
    
       outBuffer.data= pixelBuffer;
    
       outBuffer.width=CGImageGetWidth(img);
    
       outBuffer.height=CGImageGetHeight(img);
    
       outBuffer.rowBytes=CGImageGetBytesPerRow(img);
    
       error =vImageBoxConvolve_ARGB8888(&inBuffer,
    
       &outBuffer,
    
       NULL,
    
       0,
    
       0,
    
       boxSize,
    
       boxSize,
    
       NULL,
    
       kvImageEdgeExtend);
    
       if(error) {
    
       }
    
       CGColorSpaceRefcolorSpace =CGColorSpaceCreateDeviceRGB();
    
       CGContextRefctx =CGBitmapContextCreate(
    
       outBuffer.data,
    
       outBuffer.width,
    
       outBuffer.height,
     
       8,
    
       outBuffer.rowBytes,
    
       colorSpace,
    
       kCGImageAlphaNoneSkipLast);
    
       CGImageRefimageRef =CGBitmapContextCreateImage(ctx);
    
       UIImage*returnImage = [UIImageimageWithCGImage:imageRef];
    
    //clean up
    
       CGContextRelease(ctx);
    
       CGColorSpaceRelease(colorSpace);
    
       free(pixelBuffer);
    
       CFRelease(inBitmapData);
    
       CGColorSpaceRelease(colorSpace);
    
       CGImageRelease(imageRef);
    
       returnreturnImage;
    
    }
    

    15.7 图片旋转 (在原图片基础上旋转方向:左、右、下)

    - (UIImage*)sa_imageRotateWithOrientation:(UIImageOrientation)orientation {
    
       longdoublerotate =0.0;
    
       CGRectrect;
    
       floattranslateX =0;
    
       floattranslateY =0;
    
       floatscaleX =1.0;
    
       floatscaleY =1.0;
    
       switch(orientation) {
    
         caseUIImageOrientationLeft:
    
         rotate =M_PI_2;
    
         rect =CGRectMake(0,0,self.size.height,self.size.width);
    
         translateX =0;
    
         translateY = -rect.size.width;
    
         scaleY = rect.size.width/rect.size.height;
    
         scaleX = rect.size.height/rect.size.width;
    
         break;
    
       caseUIImageOrientationRight:
    
         rotate =3*M_PI_2;
    
         rect =CGRectMake(0,0,self.size.height,self.size.width);
    
         translateX = -rect.size.height;
    
         translateY =0;
    
         scaleY = rect.size.width/rect.size.height;
    
         scaleX = rect.size.height/rect.size.width;
    
         break;
    
       caseUIImageOrientationDown:
    
         rotate =M_PI;
    
         rect =CGRectMake(0,0,self.size.width,self.size.height);
    
         translateX = -rect.size.width;
    
         translateY = -rect.size.height;
    
         break;
    
       default:
    
         rotate =0.0;
    
         rect =CGRectMake(0,0,self.size.width,self.size.height);
    
         translateX =0;
    
         translateY =0;
    
       break;
     
    }
    
       UIGraphicsBeginImageContext(rect.size);
    
       CGContextRefcontext =UIGraphicsGetCurrentContext();
    
    //做CTM变换
    
       CGContextTranslateCTM(context,0.0, rect.size.height);
    
       CGContextScaleCTM(context,1.0, -1.0);
    
       CGContextRotateCTM(context, rotate);
    
       CGContextTranslateCTM(context, translateX, translateY);
    
       CGContextScaleCTM(context, scaleX, scaleY);
    
    //绘制图片
    
       CGContextDrawImage(context,CGRectMake(0,0, rect.size.width, rect.size.height),self.CGImage);
    
       UIImage*rotatedImage =UIGraphicsGetImageFromCurrentImageContext();
    
       UIGraphicsEndImageContext();
    
       returnrotatedImage;
    
    }
    

    15.8 将UIView转化成图片

    - (UIImage*)sa_getImageFromView:(UIView*)theView {
    
       UIGraphicsBeginImageContextWithOptions(theView.bounds.size,YES, theView.layer.contentsScale);
    
       [theView.layerrenderInContext:UIGraphicsGetCurrentContext()];
    
       UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
       UIGraphicsEndImageContext();
    
       returnimage;
    
    }
    

    15.9 两张图片叠加、合成

    - (UIImage*)sa_integrateImageWithRect:(CGRect)rect andAnotherImage:(UIImage*)anotherImage anotherImageRect:(CGRect)anotherRect integratedImageSize:(CGSize)size {
    
       UIGraphicsBeginImageContext(size);
    
       [selfdrawInRect:rect];
    
       [anotherImagedrawInRect:anotherRect];
    
       UIImage*integratedImage =UIGraphicsGetImageFromCurrentImageContext();
    
       UIGraphicsEndImageContext();
     
       returnintegratedImage;
    
    }
    

    15.10 图片添加水印

    /**
    
    图片添加水印
    
    @param markImage水印图片
    
    @param imgRect水印图片对于原图片的rect
    
    @param alpha水印图片透明度
    
    @param markStr水印文字
    
    @param strRect水印文字对于原图片的rect
    
    @param attribute水印文字的设置颜色、字体大小
    
    @return添加水印后的图片
    
    */
    
    - (UIImage*)sa_imageWaterMark:(UIImage*)markImage imageRect:(CGRect)imgRect markImageAlpha:(CGFloat)alpha markString:(NSString*)markStr stringRect:(CGRect)strRect stringAttribute:(NSDictionary*)attribute {
    
         UIGraphicsBeginImageContext(self.size);
    
         [selfdrawInRect:CGRectMake(0,0,self.size.width,self.size.height)blendMode:kCGBlendModeNormalalpha:1.0];
    
         if(markImage) {
    
           [markImagedrawInRect:imgRectblendMode:kCGBlendModeNormalalpha:alpha];
    
         }
    
         if(markStr) {
    
    //UILabel convertto UIImage
    
           UILabel*markStrLabel = [[UILabelalloc]initWithFrame:CGRectMake(0,0, strRect.size.width,         strRect.size.height)];
    
           markStrLabel.textAlignment=NSTextAlignmentCenter;
    
           markStrLabel.numberOfLines=0;
    
           markStrLabel.attributedText= [[NSAttributedStringalloc]initWithString:markStrattributes:attribute];
    
           UIImage*image = [selfsa_getImageFromView:markStrLabel];
    
           [imagedrawInRect:strRectblendMode:kCGBlendModeNormalalpha:1.0];;
    
     }
    
         UIImage*waterMarkedImage =UIGraphicsGetImageFromCurrentImageContext();
    
         UIGraphicsEndImageContext();
    
         return waterMarkedImage;
    
    }
    

    相关文章

      网友评论

        本文标题:iOS开发小技巧

        本文链接:https://www.haomeiwen.com/subject/nksrbttx.html