常用的代碼和技巧

特別經常使用的均可以設置爲代碼片斷,提升工做效率ios

常量的定義
web

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



懶加載的初始化

延遲加載windows

//在頭文件中定義一個屬性
@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/ app

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


1,從蘋果開發者帳戶上,請求cer的證書,而後再導出p12的證書ide

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];
相關文章
相關標籤/搜索