iOS开发小技巧

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;

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 198,082评论 5 464
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,231评论 2 375
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 145,047评论 0 327
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,977评论 1 268
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,893评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,014评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,976评论 3 388
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,605评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,888评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,906评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,732评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,513评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,980评论 3 301
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,132评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,447评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,027评论 2 343
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,232评论 2 339

推荐阅读更多精彩内容