iOS開發經驗總結2

整理了下這個幾年的筆記,看到不少的知識點都是iOS7, iOS6,iOS5的,更新換代好快啊。僅僅來回味下經常使用到基礎點,大神們請繞行。有不對的地方請你們指出,會及時修改。


1、調節UINavigationBar的leftBarButtonItem離左邊的距離 (iOS11 不可用)

UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back-button-whiteArrow.png"] style:UIBarButtonItemStylePlain target:self action:@selector(logoutBarBtnPressed:)];

UIBarButtonItem *fixedBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];

fixedBarButtonItem.width = -15;

self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:fixedBarButtonItem, buttonItem, nil];
複製代碼

距離左邊很近很近
根據 fixedButton.width配置離左邊的距離。


2、RestKit 保存數據到core data

經過RestKit將數據保存到core data中,entity爲html

@interface Article : NSManagedObject

@property (nonatomic, retain) NSNumber* articleID;
@property (nonatomic, retain) NSString* title;
@property (nonatomic, retain) NSString* body;
@property (nonatomic, retain) NSDate* publicationDate;

@end

@implementation Article // We use @dynamic for the properties in Core Data
@dynamic articleID;
@dynamic title;
@dynamic body;
@dynamic publicationDate;

@end
複製代碼

設置object mappingios

RKEntityMapping* articleMapping = [RKEntityMapping mappingForEntityForName:@"Article"
                                                      inManagedObjectStore:managedObjectStore];
[articleMapping addAttributeMappingsFromDictionary:@{
                                                     @"id": @"articleID",
                                                     @"title": @"title",
                                                     @"body": @"body",
                                                     @"publication_date": @"publicationDate"
                                                     }];

articleMapping.identificationAttributes = @[ @"articleID" ];
複製代碼

其中的identificationAttributes 設置的數組中的值,就是用來判斷返回的數據是更新仍是new。算法


3、RestKit 添加relationship

Author Entity數組

@interface Author : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *email;

@end
複製代碼

Article Entityxcode

@interface Article : NSObject

@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *body;
@property (nonatomic) Author *author;
@property (nonatomic) NSDate *publicationDate;

@end
複製代碼

添加好關係friendship緩存

// Create our new Author mapping
RKObjectMapping* authorMapping = [RKObjectMapping mappingForClass:[Author class] ];

// NOTE: When your source and destination key paths are symmetrical, you can use addAttributesFromArray: as a shortcut instead of addAttributesFromDictionary:

[authorMapping addAttributeMappingsFromArray:@[ @"name", @"email" ]];

// Now configure the Article mapping
RKObjectMapping* articleMapping = [RKObjectMapping mappingForClass:[Article class] ];
[articleMapping addAttributeMappingsFromDictionary:@{
                                                     @"title": @"title",
                                                     @"body": @"body",
                                                     @"publication_date": @"publicationDate"
                                                     }];

// Define the relationship mapping
[articleMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"author"
                                                                               toKeyPath:@"author"
                                                                             withMapping:authorMapping]];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:articleMapping
                                                                                        method:RKRequestMethodAny
                                                                                   pathPattern:nil keyPath:@"articles"
                                                                                   statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
複製代碼

在Json轉Model的時候,使用JTObjectMapping方法很相似。減小不少的工做量。bash


4、xcode找不到設備

緣由: Deployment Target版本比真機版本高,致使找不到。將Deployment Target設置成與真機的系統版本一致。網絡


5、autolayout  自動佈局

autoLayout 須要在- (void)viewDidLoad 方法執行完後生效,因此須要在- (void)viewDidAppear:(BOOL)animated 方法中再進行frame的獲取,此時才能取到正確的frame。app


6、Navigation backBarButtonItem 設置

**根據蘋果官方指出:backbarbuttonItem不能定義customview,因此,只能貼圖或者,讓leftBarButtonItem變成自定義返回按鈕,本身寫個方法進行[self.navigationController   pop當前Item **ide

以前你們是否疑惑爲何設置了相似這樣的代碼

UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                               initWithTitle:@"返回"
                               style:UIBarButtonItemStylePlain
                               target:self
                               action:nil];

self.navigationItem.backBarButtonItem = backButton;
複製代碼

界面上backButton並沒出現「返回」的字樣.

實際上是被leftBarButtonItem和rightBarButtonItem的設置方法所迷惑了leftBarButtonItem和rightBarButtonItem設置的是本級頁面上的BarButtonItem,而backBarButtonItem設置的是下一級頁面上的BarButtonItem. 好比:兩個ViewController,主A和子B,咱們想在A上顯示「刷新」的右BarButton,B上的BackButton顯示爲「撤退」就應該在A的viewDidLoad相似方法中寫:

UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc]
                                  initWithTitle:@"刷新"
                                  style:UIBarButtonItemStylePlain
                                  target:self
                                  action:nil];

self.navigationItem.rightBarButtonItem = refreshButton;

UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc]
                                 initWithTitle:@"撤退"
                                 style:UIBarButtonItemStylePlain
                                 target:self
                                 action:nil];

self.navigationItem.backBarButtonItem = cancelButton;
複製代碼

而B不須要作任何處理而後ApushB就能夠了.


7、AFNetworking 使用ssl

sharedClient.securityPolicy.allowInvalidCertificates = YES;
複製代碼

8、NSJSONSerialization 使用數據類型要求

進行JSON轉化的時候,須要知足一下的要求。

An object that may be converted to JSON must have the following properties:

  • The top level object is an NSArray or NSDictionary.
  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • All dictionary keys are instances of NSString.
  • Numbers are not NaN or infinity.

也就是說:nil,基礎數據不能轉化爲JSON。


9、NSArray進行不定參數處理

+ (NSArray *)arrayWithObjectsExceptionNil:(id)firstObj, ...
{
    NSMutableArray *tempMArray = [[NSMutableArray alloc] initWithCapacity:5];
    id eachObject = nil;
    va_list argumentList;
    
    if ( firstObj ) {
        [tempMArray addObject:firstObj];
        va_start(argumentList, firstObj);
        
        while ( (eachObject = va_arg(argumentList, id))){
            if ( nil != eachObject ){
                [tempMArray addObject:eachObject];
            }
        }
        
        va_end(argumentList);
    }
    
    return nil;
}
複製代碼

10、獲取version

NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    
    // app名稱
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    // app build版本
    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
複製代碼

**注意:appid,在申請提交的時候,在itunesconnect的這個裏面生成了,審覈經過了也不會改變。 **


11、no input file 錯誤

若是在編譯的時候找不到文件,須要先在Build Phases中的Compile Sources 將不存在的文件刪除,而後再將找不到的文件添加到project中。


12、cg,cf,ca,ui等開頭類

你還能夠看到其餘名字打頭的一些類,好比CF、CA、CG、UI等等,好比 CFStringTokenizer 這是個分詞的東東 CALayer 這表示Core Animation的層 CGPoint 這表示一個點 UIImage 這表示iPhone裏面的圖片

CF說的是Core Foundation,CA說的是Core Animation,CG說的是Core Graphics,UI說的是iPhone的User Interface


十3、file's owner 含義

file's owner 就是xib對應的類,如view對應的xib文件的file's owner對應的類就是viewcontroller的類。 file’s owner 是view和viewcontroller之間的對應關係的橋樑。(即,一個視圖,如何知道本身的界面的操做應該由誰來響應)


十4、iOS coin 不透明

通常iOS app coin應該是不透明的,而且不能夠在app中屢次使用app coin。


十5、判斷自定義類是否重複

自定義類庫中,須要重寫NSObject的兩個固定方法來判斷類是否重複:

- (BOOL)isEqual:(id)anObject;
- (NSUInteger)hash;
複製代碼

十6、IOS經常使用宏

// Macro wrapper for NSLog only if debug mode has been enabled
#ifdef DEBUG
#define DLog(fmt,...) NSLog(fmt, ##__VA_ARGS__);
#else
// If debug mode hasn't been enabled, don't do anything when the macro is called
#define DLog(...)
#endif

#define MR_ENABLE_ACTIVE_RECORD_LOGGING 0

#define IS_OS_6_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0)
#define IS_OS_7_OR_LATER    ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
#define OBJISNULL(o) (o == nil || [o isKindOfClass:[NSNull class]] || ([o isKindOfClass:[NSString class]] && [o length] == 0))
#define APP ((AppDelegate*)[[UIApplication sharedApplication] delegate])
#define UserDefaults                        [NSUserDefaults standardUserDefaults]
#define SharedApplication                   [UIApplication sharedApplication]
#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
#define RGB(r, g, b)                        [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0]
#define RGBA(r, g, b, a)                    [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]
複製代碼

十7、判斷是不是4寸屏

#define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
複製代碼

十8、NSString格式限定符

說明符 描述
%@ Objective-c 對象
%zd NSInteger
%lx CFIndex
%tu NSUInteger
%i int
%u unsigned int
%hi short
%hu unsigned short
%% %符號

十9、聲明變量 在ARC下自動初始化爲nil

NSString *s;

非ARC 的狀況下, s指向任意地址,多是系統地址,致使崩潰。

ARC 的狀況下,s已經自動初始化爲nil。


二10、向NSArray,NSDictionary等容器添加元素需判nil

[_paths addObject:[_path copy]];

若是這個_path爲nil,那麼就會出現一個crash。由於在容器中不能存放nil,能夠用[NSNull null]來保存.

推薦 pod 'XTSafeCollection', '~> 1.0.4' 第三方庫,對數組的越界,賦值nil,都有保護做用。


二11、ceil命令 floor命令

Math中一個算法命令。 函數名: ceil用 法: double ceil(double x);功 能: 返回大於或者等於指定表達式的最小整數頭文件:math.h

float f = 1.2222;
NSLog(@"f is %f.", ceil(f));
複製代碼

打印: f is 2.000000.

函數名: floor功 能: 返回小於或者等於指定表達式的最大整數用 法: double floor(double x);頭文件:math.h

float f = 1.2222;
NSLog(@"f is %f.", floor(f));
複製代碼

打印:  f is 1.000000.


二12、Xcode中對某個類進行非ARC的設置

在Xcode點擊工程,在工程中選擇「TARGETS」你的工程,在Build Phases中選擇「Compile Sources」,找到你須要設置非ARC的類,在這個類的右邊有一個「Compiler Flags」,在這個裏面設置「-fno-objc-arc  」。  那麼這個類就是非ARC進行編譯了。


二十3、storyboard上不能進行scrollview滾動

storyboard上不能進行scrollview滾動的緣由是: autolayout引發的


二十4、延長APP的啓動時間

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [NSThread sleepForTimeInterval:3.0f];

    return YES;

}
複製代碼

二十5、xcode調試的時候不運行watchdog

在利用Xcode進行調試時,watchdog不會運行,所在設備中測試程序啓動性能時,不要將設備鏈接到Xcode。


二十6、語言國際化 NSLocalizedString

若是你使用的是Localizable.strings,那麼你在程序中能夠這樣獲取字符串: NSLocalizedString(@"mykey", nil)   若是你使用的是自定義名字的.strings,好比MyApp.strings,那麼你在程序中能夠這樣獲取字符串:   NSLocalizedStringFromTable (@"mykey",@"MyApp", nil)   這樣便可獲取到"myvalue"這個字符串,能夠是任何語言。


二十7、UIAppearance 使用

使用UIAppearance進行外觀的自定義。

[+ appearance]修改整個程序中某個class的外觀

[[UINavigationBar appearance] setTintColor:myColor];
複製代碼

[+ appearanceWhenContainedIn:] 當某個class被包含在另一個class內時,才修改外觀。

 [[UILabel appearanceWhenContainedIn:[cusSearchBar class], nil] setTextColor:[UIColor redColor]];
複製代碼

二十8、將NSString轉換成UTF8編碼的NSString

在使用網絡地址時,通常要先將url進行encode成UTF8格式的編碼,不然在使用時可能報告網址不存在的錯誤,這時就須要進行轉換 下面就是轉換函數:

NSString *urlString= [NSString stringWithFormat:@"http://www.baidu.com"];
NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)urlString, NULL, NULL,  kCFStringEncodingUTF8 ));
NSURL *url = [NSURL URLWithString:encodedString];
複製代碼

或者使用下面的方法:

NSString *utf8Str = @"Testing";
NSString *unicodeStr = [NSString stringWithCString:[utf8Str UTF8String] encoding:NSUnicodeStringEncoding];
複製代碼

有時候獲取的url中的中文等字符是亂碼,網頁內容是亂碼,須要進行一下轉碼才能正確識別NSString,能夠用下面的方法:

//解決亂碼問題()

NSString *transString = [NSString stringWithString:[string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
複製代碼

二十9、NSDateFormatter設定日期格式 AM

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setAMSymbol:@"AM"];
[dateFormatter setPMSymbol:@"PM"];
[dateFormatter setDateFormat:@"dd/MM/yyyy hh:mmaaa"];
NSDate *date = [NSDate date];
    
NSString *s = [dateFormatter stringFromDate:date];
複製代碼

顯示效果爲: 10/05/2010 03:49PM


三10、判斷NSString爲純數字

//判斷是否爲整形:

- (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

//判斷是否爲浮點形:

- (BOOL)isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}

if( ![self isPureInt:insertValue.text] || ![self isPureFloat:insertValue.text])
{
    resultLabel.textColor = [UIColor redColor];
    
    resultLabel.text = @"警告:含非法字符,請輸入純數字!";
    
    return;
}
複製代碼

三11、image的正確使用

iOS中從程序bundle中加載UIImage通常有兩種方法。 第一種比較常見:imageNamed 第二種方法不多使用:imageWithContentsOfFile   爲何有兩種方法完成一樣的事情呢?imageNamed的優勢在於能夠緩存已經加載的圖片。蘋果的文檔中有以下說法: This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.   這種方法會在系統緩存中根據指定的名字尋找圖片,若是找到了就返回。若是沒有在緩存中找到圖片,該方法會從指定的文件中加載圖片數據,並將其緩存起來,而後再把結果返回。   而imageWithContentsOfFile方法只是簡單的加載圖片,並不會將圖片緩存起來。這兩個方法的使用方法以下:

UIImage *img = [UIImage imageNamed:@"myImage"]; // caching  
// or  
UIImage *img = [UIImage imageWithContentsOfFile:@"myImage"]; // no caching 
複製代碼

那麼該如何選擇呢?   若是加載一張很大的圖片,而且只使用一次,那麼就不須要緩存這個圖片。這種狀況imageWithContentsOfFile比較合適——系統不會浪費內存來緩存圖片。

然而,若是在程序中常常須要重用的圖片,那麼最好是選擇imageNamed方法。這種方法能夠節省出每次都從磁盤加載圖片的時間。


三12、將圖片中間部分放大

根據圖片上下左右4邊的像素進行自動擴充。

UIImage *image = [UIImage imageNamed:@"png-0016"];
UIImage *newImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(50, 50, 50, 50) resizingMode:UIImageResizingModeStretch];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 200, 400)];
imageView.image = newImage;
imageView.contentMode = UIViewContentModeScaleAspectFill;
複製代碼

使用方法- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode NS_AVAILABLE_IOS(6_0); // the interior is resized according to the resizingMode 進行對圖片的拉伸,可使用UIImageResizingModeTile和UIImageResizingModeStretch兩種拉伸方式。 **注意: **此方法返回一個新的UIImage,須要使用這個新的image。

注:UIEdgeInsets設置的值不要上下或左右交叉,否則會出現中間爲空白的狀況。

在Xcode5中也可使用新特性 Slicing,直接對圖片進行設置,不須要在代碼中設置了。


三十3、UIImage和NSData的轉換

NSData *imageData = [NSData dataWithContentsOfFile:imagePath];
UIImage *aimage = [UIImage imageWithData:imageData];
//UIImage 轉化爲 NSData
NSData *imageData = UIImagePNGRepresentation(aimage);
複製代碼

三十4、NSDictionary和NSData轉換

// NSDictionary -> NSData:
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];
    
// NSData -> NSDictionary:
NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];
複製代碼

三十5、NSNumberFormatter 價格採用貨幣模式

若是顯示的數值爲價格,則用貨幣模式

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
self.introView.guaranteedDataLabel.text = [formatter stringFromNumber:self.quoteEntity.guranteedInfo.guaranteedPrice];
複製代碼

三十6、畫虛線的方法

CGFloat lengths[] = {5, 5};

CGContextRef content = UIGraphicsGetCurrentContext();

CGContextBeginPath(content);

CGContextSetLineWidth(content, LINE_WIDTH);

CGContextSetStrokeColorWithColor(content, [UIColor blackColor].CGColor);

CGContextSetLineDash(content, 0, lengths, 2);

CGContextMoveToPoint(content, 0, rect.size.height - LINE_WIDTH);

CGContextAddLineToPoint(content, rect.size.width, rect.size.height - LINE_WIDTH);

CGContextStrokePath(content);

CGContextClosePath(content);
複製代碼

三十7、設備轉屏

- (BOOL)shouldAutorotate
{
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscapeLeft;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationLandscapeLeft;
}
複製代碼

在storyboard中設置只支持豎屏,能夠在單個UIViewController中加入這3個方法,使得這個UIViewController只支持左橫屏。


三十8、UITextField  彈出UIDatePicker

設置UITextField的inputView能夠不彈出鍵盤,而彈出UIDatePicker。

首先須要在View加載結束的時候指定文本的InputView

UIDatePicker *datePicker = [[UIDatePicker alloc] init];  
datePicker.datePickerMode = UIDatePickerModeDate;  
[datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];  
self.txtDate.inputView = datePicker;  
複製代碼

而後須要指定當UIDatePicker變更的時候的事件是什麼. 此處就是爲了給文本框賦值.

- (IBAction)dateChanged:(id)sender  
{  
    UIDatePicker *picker = (UIDatePicker *)sender;  
    self.txtDate.text = [NSString stringWithFormat:@"%@", picker.date];
   
}  
複製代碼

而後當文本框編輯結束時, 須要讓UIDatePicker消失.

- (IBAction)doneEditing:(id)sender  
{  
    [self.txtDate resignFirstResponder];  
}  
複製代碼

而後把文本框在IB中, 指向定義好的txtDate就好了~


三十9、將Status Bar字體設置爲白色

  1. 在Info.plist中設置UIViewControllerBasedStatusBarAppearance爲NO

  2. 在須要改變狀態欄顏色的ViewController中在ViewDidLoad方法中增長:

UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
複製代碼

若是須要在所有View中都變色,能夠寫在父類的相關方法中。


四10、UILongPressGestureRecognizer執行2次的問題

//會調用2次,開始時和結束時
- (void)hello:(UILongPressGestureRecognizer *)longPress
{
    if (longPress.state == UIGestureRecognizerStateEnded)//須要添加一個判斷
    {
        NSLog(@"long");
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"hello"
                              
                                                        message:@"Long Press"
                              
                                                       delegate:self
                              
                                              cancelButtonTitle:@"OK"
                              
                                              otherButtonTitles:nil, nil];
        
        [alert show];
    }
}

複製代碼

四11、View中事件一次響應一個

self.scrollView.exclusiveTouch = YES;
複製代碼

設置exclusiveTouch這個屬性爲YES。


四12、UIScrollView中當即響應操做

delaysContentTouches 屬性是UIScrollView中當即響應Touch事件。默認是YES,若是想點擊後立刻有反應,則將該值設置爲NO。


四十3、UITableView在Cell上添加自定義view

若是在UITableView上添加一個自定義的UIView,須要注意在view中的顏色會由於Cell被選中的點擊色,而引發view的顏色變化,而且不可逆。


四十4、NSNotificationCenter 註銷

當 NSNotificationCenter 註冊一個通知後

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullableNSString *)aName object:(nullableid)anObject;
複製代碼

在class的dealloc中,必定要使用

- (void)removeObserver:(id)observer name:(nullable NSString *)aName object:(nullable id)anObject;
複製代碼

進行註銷。

不能用 - (void)removeObserver:(id)observer;進行通知的註銷。

注意: 若是不註銷,將致使class不會被釋放。


四十5、H5開發的弊端

H5開發的弊端: 佔用內容太多。在打開H5的時候,會佔用大量的內存,在項目中看到,通常會達到一個頁面50M的內存。


四十6、interactivepopgesturerecognizer 使用

設置left bar button後,會致使右滑返回的效果失效,查看完美的設置方案。

同時爲了獲取到右滑返回的事件,能夠執行

[self.navigationController.interactivePopGestureRecognizer addTarget:self action:@selector(back)];
複製代碼

**在ViewController中viewDidAppare中添加,在viewWillDisappear中remove。 **


四十7、masonry 中使用兩個UIView之間設置layout

[self.bottomOpenStoreBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(promptImageView.mas_bottom).with.offset(30);
        make.height.mas_equalTo(44);
        make.width.mas_equalTo(SCREEN_WIDTH - 30);
        make.centerX.mas_equalTo(self.promptScrollView);
        make.bottom.mas_equalTo(self.promptScrollView.mas_bottom).with.offset(-30);
    }];
複製代碼

設置self.bottomOpenStoreBtn的頂部與promptImageView的頂部距離30pt make.bottom.mas_equalTo(self.promptScrollView.mas_bottom).with.offset(-30); 其中的 self.promptScrollView.mas_bottom 必須使用mas_bottom,不能使用bottom.

make.top 中的top爲  - (MASConstraint*)top 而 self.promptScrollView.bottom 中的bottom爲

- (float) bottom
{    return CGRectGetMaxY (self.frame);
}
複製代碼

即一個是layout屬性,另外一個爲frame的屬性。

相關文章
相關標籤/搜索