当前位置: 首页 > news >正文

经常使用的代码和技巧

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

特别常用的都可以设置为代码片段,提高工作效率

常量的定义

http://www.xiaoyaoli.com/?p=929



懒加载的初始化

延迟加载

//在头文件中定义一个属性
@property (nonatomic,strong) NSMutableArray *shopDataArray; /**< 店铺数据的数组 */

//在实现文件中实现
-(NSMutableArray *)shopDataArray{
    if(!_shopDataArray){
        _shopDataArray=[[NSMutableArray alloc]init];
    }
    return _shopDataArray;
}



1,设置多行label的间距

 self.view.backgroundColor=[UIColor whiteColor];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(100, 100, 200, 300)];
    label.numberOfLines=0;
    label.backgroundColor=[UIColor greenColor];
    [self.view addSubview:label];
    
    NSDictionary *attrsDictionary2 = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:14.0] forKey:NSFontAttributeName];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineHeightMultiple:3.0];//调整行间距
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    NSString *testString=@"测试一下多行的效果.测试一下多行的效果.测试一下多行的效果.测试一下多行的效果.\n测试一下多行的效果\n测试一下多行的效果";
    
    NSMutableAttributedString *mutableAttributedString=[[NSMutableAttributedString alloc]initWithString:testString attributes:attrsDictionary2];
    [mutableAttributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, testString.length)];//(testString)];
    label.attributedText=mutableAttributedString;


2, 枚举类型


typedef NS_ENUM (NSUInteger, PNChartFormatType) {
    PNChartFormatTypePercent,
    PNChartFormatTypeDollar,
    PNChartFormatTypeNone
};


编译器适配

#ifdef __IPHONE_7_0
//在iOS SDK 7.0以后执行这部分编译
#else
//在iOS SDK 7.0之前执行这部分编译
#endif


极光推送证书的设置

看官方文档就好了一步一步操作

http://docs.jpush.io/client/ios_tutorials/

http://docs.jpush.cn/pages/viewpage.action?pageId=2621727


1,从苹果开发者账户上,请求cer的证书,然后再导出p12的证书

2,将p12的证书提交到极光。

3,设置app的配置文件

4,倒入sdk,配置key等信息

好了以后随便推个 你好之类的,但是应用必须在后台才可以,在前台代理方法会执行,但是界面上看不到效果的。


获得文件所在路径

NSString *path=[[NSBundle mainBundle] pathForResource:@“Notes” ofType:@“xml”];


设置状态栏网络访问的状态

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];



拨打电话

if (_webView == nil) {
    _webView = [[UIWebView alloc] initWithFrame:CGRectZero];
}
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"tel://10010"]]];

//需要注意的是:这个webView千万不要添加到界面上来,不然会挡住其他界面


发短信

方法一

//直接跳到发短信界面,但是不能指定短信内容,而且不能自动回到原应用
NSURL *url = [NSURL URLWithString:@"sms://10010"];
[[UIApplication sharedApplication] openURL:url];

方法二

//如果想指定短信内容,那就得使用MessageUI框架
//包含主头文件
#import <MessageUI/MessageUI.h>

//显示发短信的控制器
MFMessageComposeViewController *vc = [[MFMessageComposeViewController alloc] init];
// 设置短信内容
vc.body = @"吃饭了没?";
// 设置收件人列表
vc.recipients = @[@"10010", @"02010010"];
// 设置代理
vc.messageComposeDelegate = self;

// 显示控制器
[self presentViewController:vc animated:YES completion:nil];

//代理方法,当短信界面关闭的时候调用,发完后会自动回到原应用
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    // 关闭短信界面
    [controller dismissViewControllerAnimated:YES completion:nil];
    
    if (result == MessageComposeResultCancelled) {
        NSLog(@"取消发送");
    } else if (result == MessageComposeResultSent) {
        NSLog(@"已经发出");
    } else {
        NSLog(@"发送失败");
    }
}



打开网页



发邮件


//用自带的邮件客户端,发完邮件后不会自动回到原应用
NSURL *url = [NSURL URLWithString:@"mailto://10010@qq.com"];
[[UIApplication sharedApplication] openURL:url];


apple store评价跳转

//方法1
NSString *appid = @"444934666";
NSString *str = [NSString stringWithFormat:
                 @"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@", appid];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];

方法2
NSString *str = [NSString stringWithFormat:
                 @"itms-apps://itunes.apple.com/cn/app/id%@?mt=8", appid];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];




显示的应用名称

修改这个属性

Bundle display name


判断系统版本

  if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories

显示windows

   self.window.rootViewController=vc;
    [self.window makeKeyAndVisible];


indexPath 初始化

   NSIndexPath *index=[[NSIndexPath alloc]initWithIndexes:1 length:1];

UINavigationBar 上面的按钮间距

 UIBarButtonItem *flexibleSpaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:@selector(btnClick:)];
NSArray *arr = @[item0,flexibleSpaceItem,item1];
 self.navigationItem.leftBarButtonItems = arr;

Unicode和NSString转换

NSString转Unicode

NSString *a = @"test";
char *b = [a cStringUsingEncoding:NSUnicodeStringEncoding];

单个Unicode转NSString

@"\U8ba" 作为参数  获得@"认"

+(NSString *)replaceUnicode:(NSString *)unicodeStr {
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u"withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\""withString:@"\\\""];
    NSString *tempStr3 = [[@"\""stringByAppendingString:tempStr2]stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString* returnStr = [ NSPropertyListSerialization propertyListFromData:tempData
                    mutabilityOption:NSPropertyListImmutable
                            format:NULL
                            errorDescription:NULL];

    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n"withString:@"\n"];
}


tableview的滚动

tableview向下滚动180个高度

   [self.tableView setContentOffset:CGPointMake(0,180) animated:YES];

滚动某个cell到指定位置

  [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];


tableview缩进

[self.tabelview setContentInset:UIEdgeInsetsMake(-100, 0, 0, 0)];


UITextField的代理和消息


监听消息

在viewWillAppear里面监听,在viewWillDisappear里面取消监听

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}


UITextField的键盘


inputAccessoryViewinputView


定义一个类的属性


@property (nonatomic, assign) Class destVC;

从JSON串创建OC object

        NSString *path = [[NSBundle mainBundle] pathForResource:@"product.json" ofType:nil];
        // 2.2根据全路径加载json文件到nsdata中
        NSData *data = [NSData dataWithContentsOfFile:path];
        // 2.3将加载进来的nsdata数据转换为OC中对应的对象
        NSArray *dictArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL];


block作为参数

typedef  void (^optionBlcok)();
@property (nonatomic, copy) optionBlcok option;


从story board初始化

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {

      
        NSLog(@"initWithCoder");
    }
    return self;
}


从xib创建view的初始化

- (void)awakeFromNib
{
    // 设置图片的主图层圆角
    self.iconView.layer.cornerRadius = 8;
    // 设置超出主图层的部分剪切
    self.iconView.clipsToBounds = YES;

}


设置TableView Cell的样式

在cell的initWith方法里面设置

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

    // 1.设置cell选中状态的背景颜色
    UIView *selView = [[UIView alloc] init];
    selView.backgroundColor = NJColor(232, 228, 209);
    self.selectedBackgroundView = selView;
    // 2.设置cell默认状态的背景颜色
    UIView *norView = [[UIView alloc] init];
    norView.backgroundColor = [UIColor whiteColor];
    self.backgroundView = norView;
    
   
    //设置accessory view
    self.accessoryView = self.switchBtn;


从一个小图片平铺获得背景图片

//设置tableview的background
    self.tableView.backgroundColor =  [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg"]];
    // 清空系统的backgroundView
    self.tableView.backgroundView = nil;


block 避免循环引用

 __weak typeof (self) unsafeSelf=self;
 __weak NJViewController *unsafeSelf=self;
 __unsafe_unretained NJViewController *unsafeSelf=self;


一个pixel对应的像素

[UIScreen mainScreen].scale




剪切图片

CGImageCreateWithImageInRect


UIImage *norImage = [UIImage imageNamed:@"LuckyAstrology"];
CGFloat imageH = NJImageHeight * [UIScreen mainScreen].scale;
CGFloat imageW = NJImageWidth * [UIScreen mainScreen].scale;
CGFloat imageY = 0;
CGFloat imageX = index * imageW;
CGRect rect = CGRectMake(imageX, imageY, imageW, imageH);
// 8.1根据rect切割图片
// CGImage中rect是当做像素来使用
// UIKit 中是点坐标系
// 坐标系的特点:如果在非retain屏上 1个点等于1个像素
//  在retain屏上1个点等于2个像素
// 剪切默认状态的图片
CGImageRef norCGImageRef= CGImageCreateWithImageInRect(norImage.CGImage, rect);
// 将切割好的图片转换为uiimage设置为按钮的背景
[btn setImage:[UIImage imageWithCGImage:norCGImageRef]  forState:UIControlStateNormal];


自定义UIButton


重新布置imageview的大小和位置

- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    CGFloat imageX = (contentRect.size.width - NJImageWidth ) * 0.5;
    CGFloat imageY = 18;
    return CGRectMake(imageX, imageY, NJImageWidth, NJImageHeight);
}


取消Button的高亮状态


- (void)setHighlighted:(BOOL)highlighted
{
    
}


标记和组织语言

// TODO: 需要做的
// MARK:标记 1
// FIXME: error 1错误1
#warning 警告 需要自定义内容
#pragma mark 代码分段



从数组中取第一个元素

[array objectAtIndex:0];

//如果数组为空会报错,但是如果你用[NSArray firstObject]方法是不会有这个问题的,会返回nil
[array firstObject];


版本号信息

    // 如何知道第一次使用这个版本?比较上次的使用情况
    NSString *versionKey = (__bridge NSString *)kCFBundleVersionKey;
    
    // 从沙盒中取出上次存储的软件版本号(取出用户上次的使用记录)
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *lastVersion = [defaults objectForKey:versionKey];
    
    // 获得当前打开软件的版本号
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[versionKey];



转载于:https://my.oschina.net/u/2360054/blog/490464

相关文章:

  • Java存储区域——JVM札记lt;一个gt;
  • memset函数详解
  • Migration workstation vms to openstack kvm
  • Scala学习笔记(1)-环境搭建
  • Android平台调用Web Service:螺纹的引入
  • sed去掉文件中的空行
  • 前端手札--meta标记篇
  • 小技巧:Windows Server 2012R2 WiFi 无法连接问题
  • 在项目中引入领域驱动设计的经验
  • 【零基础学习iOS开发】【02-C语言】11-函数的声明和定义
  • 树莓派 安装 php
  • 互联网架构设想的大型应用软件,并建议
  • Android软硬整合技术(HALFramework)
  • httpry 升级版本 secihttp 发布了
  • 认为最重要的是:不要说自己正在「创业」(转)
  • IE9 : DOM Exception: INVALID_CHARACTER_ERR (5)
  • angular组件开发
  •  D - 粉碎叛乱F - 其他起义
  • JS创建对象模式及其对象原型链探究(一):Object模式
  • laravel 用artisan创建自己的模板
  • learning koa2.x
  • mysql 数据库四种事务隔离级别
  • Protobuf3语言指南
  • python_bomb----数据类型总结
  • Spark in action on Kubernetes - Playground搭建与架构浅析
  • 阿里云爬虫风险管理产品商业化,为云端流量保驾护航
  • 基于Android乐音识别(2)
  • 基于阿里云移动推送的移动应用推送模式最佳实践
  • 理解 C# 泛型接口中的协变与逆变(抗变)
  • 名企6年Java程序员的工作总结,写给在迷茫中的你!
  • 前端面试之CSS3新特性
  • 区块链将重新定义世界
  • 入门到放弃node系列之Hello Word篇
  • 深入浅出webpack学习(1)--核心概念
  • 我看到的前端
  • 小程序button引导用户授权
  • [Shell 脚本] 备份网站文件至OSS服务(纯shell脚本无sdk) ...
  • 长三角G60科创走廊智能驾驶产业联盟揭牌成立,近80家企业助力智能驾驶行业发展 ...
  • #pragma预处理命令
  • (14)目标检测_SSD训练代码基于pytorch搭建代码
  • (C#)一个最简单的链表类
  • (二)换源+apt-get基础配置+搜狗拼音
  • (二开)Flink 修改源码拓展 SQL 语法
  • (离散数学)逻辑连接词
  • (区间dp) (经典例题) 石子合并
  • (一)pytest自动化测试框架之生成测试报告(mac系统)
  • (原创)Stanford Machine Learning (by Andrew NG) --- (week 9) Anomaly DetectionRecommender Systems...
  • .bat批处理出现中文乱码的情况
  • .L0CK3D来袭:如何保护您的数据免受致命攻击
  • .Net 4.0并行库实用性演练
  • .NET 4.0网络开发入门之旅-- 我在“网” 中央(下)
  • .net core开源商城系统源码,支持可视化布局小程序
  • .NET Framework Client Profile - a Subset of the .NET Framework Redistribution
  • .NET6 开发一个检查某些状态持续多长时间的类
  • .NET和.COM和.CN域名区别