iOS項目開發中的知識點與問題收集整理②

一、點擊UIButton 沒法產生觸摸事件   

若是在UIImageView中添加了一個按鈕,你會發如今默認狀況下這個按鈕是沒法被點擊的,須要設置UIImageView的userInteractionEnabled爲YES:

imageView.userInteractionEnabled = YES;
設置爲YES後,UIImageView內部的按鈕就能夠被點擊了  html

二、如何啓動app時全屏顯示Default.png(圖片)?  

大部分app在啓動過程當中全屏顯示一張背景圖片,好比新浪微博會顯示這張:



要想在iOS中實現這種效果,毫無壓力,很是地簡單,把須要全屏顯示的圖片命名爲Default.png便可,在iOS app啓動時默認會去加載並全屏顯示Default.png。

也能夠用其餘名稱來命名圖片,在Info.plist配置一下便可:



配置事後,app啓動時就會去加載並全屏顯示lufy.png

在默認狀況下,app顯示Default.png時並不是真正的"全屏顯示",由於頂部的狀態欄並無被隱藏,好比下面的效果:


大部分狀況下,咱們都想隱藏狀態欄,讓Default.png真正全屏顯示。

說到這裏,可能有人立刻就想到了一種辦法:在AppDelegate的application:didFinishLaunchingWithOptions:方法中添加以下代碼:

[UIApplication sharedApplication].statusBarHidden = YES;
我只能說你的思路是對的,但實際上達不到想要的效果,你會發現顯示Default.png時狀態欄仍是存在的,等Default.png顯示完畢後,狀態欄才被隱藏。

我先解釋下爲何這種方法不可行,其實緣由很簡單:

1> Default.png是在app啓動過程當中加載的,並非在app啓動完畢後再加載的

2> AppDelegate的application:didFinishLaunchingWithOptions:方法是在app啓動完畢後才調用的

下面說一下解決方案,在Info.plist中增長一個配置便可:



這裏的YES表示在app初始化(啓動)的時候就隱藏狀態欄。

固然,在Default.png顯示完畢後狀態欄仍是隱藏的。若是想從新顯示狀態欄,補上下面代碼便可:

[UIApplication sharedApplication].statusBarHidden = NO; vue

三、使用ASIHTTPRequest保存cookies   

假如個人APP,第一次啓動請求了登陸接口並獲得了Cookie,而後我把APP關了,下次啓動APP,我不請求登陸接口了,java

那上次獲得的Cookie就不存在了。若是須要,那麼2種方法,下次啓動app,自動登入,這樣能獲得服務器分配給你的cookierios

(這一種是最好的,由於session也會過時),還有一種是你把上次登入的時候,拿到的cookier存起來,而後下次啓動app的時候,c++

手動給請求(ASIHTTP)添加cookie。因此當第一次登陸成功後,能夠把cookie保存到CoreData,SQLite,UserDefault等,git

等到下次網絡請求時,讀取:  ajax

1  ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:UserInfoURL]; 2 [request setRequestMethod:@"POST"]; 3  [request addRequestHeader:@"Cookie" value:[NSString stringWithFormat:@"cookie=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"cookie"]]]; 4 //把cookie的值放進Header裏,這個cookie的值是一串很長的字符串。 
View Code

四、設置UITextField只有當有字符輸入後,鍵盤右下角的搜索/返回/done/等等鍵纔可使用  

TextField設置這個屬性爲YES就能夠了,默認爲NO

searchField.enablesReturnKeyAutomatically =YES;


算法

五、相似QQ等IM軟件,長度和高度不一的聊天氣泡的圖片是如何作的?拉伸?  


實際上是一個小氣泡png,而後拉伸中間部分,四個角不拉動,就是局部拉伸。ios自帶方法,四個角能夠不拉伸的,以下:

sql

六、UITableView中有多個UITextField時,被擋住的TextField如何實現自動向上彈起?   

首先要實現TextField的delegate,在方法:    npm

1 - (void)textFieldDidBeginEditing:(UITextField *)textField { 2     [self.tableView setContentOffset:CGPointMake(0, 70) animated:YES]; 4 }  
View Code

這說明當開始輸入時,tableview在原來的基礎上向上擡起70個距離。多個UITextFiled能夠經過判斷來使用CGPoint的調整高度,我這寫的是70.
tableview的scrollEnabled屬性必定要是YES;要否則滾動不了了。
記得在return時復原tableview的位置:  

1 - (BOOL)textFieldShouldReturn:(UITextField *)sender { 2     [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES]; 3     return YES; 4 }   
View Code

七、ios如何在調試時,輕鬆找到程序在哪裏崩潰?  

咱們給本身的工程添加一個全局的斷點:
 

一步步按上面圖完成操做。
再運行程序

自動就斷點到這裏來了,
log信息是:

2013-05-20 11:14:19.635 GestureRecognizer[1491:c07] -[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x7a88df0  
2013-05-20 11:15:21.148 GestureRecognizer[1491:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x7a88df0'

這樣很簡單就能發現程序崩潰是由於value沒有 isEqualToString方法。若是沒加上面這個通用的斷點,那程序會直接斷點到main函數去。

八、UIImageView 如何實現windows 桌面相似的背景壁紙屏幕(很小的圖片會顯示N多個)? 

從UImageView上找ContentMode或clipToBounds是都無論用的,正確的辦法是,不用UImageView,使用UIView,而後設置backgroundColor屬性爲咱們的圖片,這樣的話自動會以屏幕的方式顯示。

1 UIView *gridView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 195)]; 2 gridView.backgroundColor = [UIColor colorWithPatternImage:BUNDLE_IMAGE(@"blue_grid")]; 3 [self.view addSubview:gridView]; 4 [gridView release];  

下圖所示:(原圖是一個6X6的方格)

九、UITableViewCell 的backgroundColor不起做用的問題?   

在開發時,想要在tableview中的某一個Cell設置選中狀態,而且Cell的背景顏色是一個自定義顏色。

 1 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 2       
 3 <span style="white-space:pre">  </span>//省略.... 
 5     cell.textLabel.font = [UIFont systemFontOfSize:6.0]; 6     cell.textLabel.text = @"13832207020"; 7  
 8     if (indexPath.row==0) { 10         [cell setBackgroundColor:[UIColor colorWithRed:100.0f/255.0f green:176.0f/255.0f blue:0.0f/255.0f alpha:1.0f]]; 11 } 12     else{ 13 [cell setBackgroundColor:[UIColor whiteColor]]; 14 } 15       
16     return cell; 17 }   
View Code 

這樣的話,第1行cell就應該是咱們設置好的顏色,不過請注意,此方法在UITableViewStylePlain的風格下有效,在 UITableViewStyleGrouped的樣式下是無效的!這個跟tableview的backgroundView和backgroundColor是沒有關係的,我的猜測應該是在Grouped風格下,cell選中的顏色有系統的view遮罩,致使咱們設置的沒法顯示出來。
【補充】若是想在reload或init時設置tableview的某一cell爲 selected狀態,千萬不要使用cell setSelected:YESanimated:YES,使用tableview的方法:

1 NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0]; 2 terminalTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];   

十、UITableViewCell選中時contentView中各組件的高亮狀態   

使用系統或簡單自定義的UITableViewCell時,當選中某一行Cell後,除了背景顏色改變外,Cell上全部的組件(數據)好比UILabel,UIbutton等都被自動顯示成了其

Highlighted(高亮)狀態下的效果,(若是想顯示出效果,你的那些自定義的組件必需要設置高亮狀態,好比highlightedTextColor,UIControlStateHighlighted等),

因此這一點須要特別注意,若是不想要系統的這個自動特效,有兩個解決辦法:

1,組件不設置highlighted下的屬性

2,若是自定義的Cell:

 1 - (void)setSelected:(BOOL)selected animated:(BOOL)animated 2 { 4 [super setSelected:selected animated:animated]; 6     if (selected) { 7         //強制系統在UITableViewCell選中時SettingButton組件的高亮狀態爲NO 
 8         [(UIButton *)[self.contentView.subviews objectAtIndex:1] setHighlighted:NO]; 9         [settingBtn setImage:BUNDLE_IMAGE(@"accessory_sel") forState:UIControlStateNormal]; 10 } 11     else{ 12         [settingBtn setImage:BUNDLE_IMAGE(@"accessory_nor") forState:UIControlStateNormal]; 13 } 16 }     
View Code

十一、IOS atomic與nonatomic,assign,copy與retain的定義和區別   

atomic和nonatomic用來決定編譯器生成的getter和setter是否爲原子操做。
        atomic
                設置成員變量的@property屬性時,默認爲atomic,提供多線程安全。
                在多線程環境下,原子操做是必要的,不然有可能引發錯誤的結果。加了atomic,setter函數會變成下面這樣:
                        {lock}
                                if (property != newValue) {
                                        [property release];
                                        property = [newValue retain];
                                }
                        {unlock}
        nonatomic
        禁止多線程,變量保護,提升性能。
        atomic是Objc使用的一種線程保護技術,基本上來說,是防止在寫未完成的時候被另一個線程讀取,形成數據錯誤。而這種機制

        是耗費系統資源的, 因此在iPhone這種小型設備上,若是沒有使用多線程間的通信編程,那麼nonatomic是一個很是好的選擇。

        指出訪問器不是原子操做,而默認地,訪問器是原子操做。這也就是說,在多線程環境下,解析的訪問器提供一個對屬性的安全訪

         問,從獲取器獲得的返回值或者經過設置器設置的值能夠一次完成,即使是別的線程也正在對其進行訪問。若是你不指定 nonato

       mic,在 本身管理內存的環境中,解析的訪問器保留並自動釋放返回的值,若是指定了 nonatomic ,那麼訪問器只是簡單地返回

      這個值。

assign
        對基礎數據類型 (NSInteger,CGFloat)和C數據類型(int, float, double, char)等等。
        此標記說明設置器直接進行賦值,這也是默認值。在使用垃圾收集的應用程序中,若是你要一個屬性使用assign,且這個類符合

        NSCopying協 議, 你就要明確指出這個標記,而不是簡單地使用默認值,不然的話,你將獲得一個編譯警告。這再次向編譯器

        說明你確實須要賦值,即便它是可拷貝的。


retain
        對其餘NSObject和其子類對參數進行release舊值,再retain新值
        指定retain會在賦值時喚醒傳入值的retain消息。此屬性只能用於Objective-C對象類型,而不能用於Core Foundation對象。

        (緣由很明顯,retain會增長對象的引用計數,而基本數據類型或者Core Foundation對象都沒有引用計數——譯者注)。

        注意: 把對象添加到數組中時,引用計數將增長對象的引用次數+1。

copy
        對NSString 它指出,在賦值時使用傳入值的一份拷貝。拷貝工做由copy方法執行,此屬性只對那些實行了NSCopying協議

        的對象類型有效。更深刻的討論 ,請參考「複製」部分。


copy與retain:
Copy實際上是創建了一個相同的對象,而retain不是:
1.好比一個NSString 對象,地址爲0×1111 ,內容爲@」STR」,Copy 到另一個NSString 以後,地址爲0×2222 ,內容相同。
2.新的對象retain爲1 ,舊有對象沒有變化retain 到另一個NSString 以後,地址相同(創建一個指針,指針拷貝),內容固然相同,

   這個對象的retain值+1。
總結:retain 是指針拷貝,copy 是內容拷貝。

assign與retain:
1. 接觸過C,那麼假設你用malloc分配了一塊內存,而且把它的地址賦值給了指針a,後來你但願指針b也共享這塊內存,因而你又

   把a賦值 給(assign)了b。 此時a和b指向同一塊內存,請問當a再也不須要這塊內存,可否直接釋放它?答案是否認的,由於a並不

   知道b是否還在 使用這塊內存,若是a釋放了,那麼b在使用這塊內存的時候會引發程序crash掉。

2. 瞭解到1中assign的問題,那麼如何解決?最簡單的一個方法就是使用引用計數(reference counting),仍是上面的那個例子,

    咱們給 那塊內存設一個引用計數, 當內存被分配而且賦值給a時,引用計數是1。當把a賦值給b時引用計數增長到2。這時若是a

    再也不使用這塊內存, 它只須要把引用計數減1,代表本身再也不擁有這塊內存。b再也不使用這塊內存時也把引用計數減1。當引用計數

     變爲0的時候,表明該內存再也不  被任何指針所引用,系統能夠把它直接釋放掉。

總結:

           上面兩點其實就是assign和retain的區別,assign就是直接賦值,從而可能引發1中的問題,當數據爲int, float等原生類型時,

            可使用assign。retain就如2中所述,使用了引用計數,retain引發引用計數加1, release引發引用計數減1,當引用計數爲

            0時,dealloc函數被調用,內存被回收。  

十二、#pragma mark -#pragma mark Initialization含義  

它們告訴Xcode編譯器,要在編輯器窗格頂部的方法和函數彈出菜單中將代碼分隔開;注意 #pragma mark – 的「-」後面不能有空格。若是你的標誌沒有

出如今彈出菜單中,好比沒有分隔線出現,請在Xcode菜單 「Preferences..」中的 「Code Sense」選項取消選中」Sort listalphabetically」便可。

1三、自定義delegate變量聲明時使用assign仍是retain?   

咱們經過發送消息給對象出發特定動做;對象發送某些變化的時候經過回調函數(callback)通知咱們。對象在特定事件發生的時候,就會調用對應的回調函數,

觸發業務邏輯。回調函數經過所謂的代理(Delegation)來實現.

delegate使用方法:

@property (assign) <id>xxxDelegate delegate;

  正確的使用方法是使用assign屬性而不是retain。之因此對於delegate這類對象使用assign而不是用retain是爲了防止循環retain(retain loop)

1四、給成員變量(屬性)賦值時使不使用self?   

使用@property和@synthesize聲明一個成員變量,給其賦值是時要在前面加上"self.",以便調用成員變量的setmember方法。直接調用成員變量而且給其賦值:

member=[NSString stringWithFormat:@」」];將不執行setmember 方法。
使用self調用成員變量而且給其賦值:self.member=[NSString stringWithFormat:@」」];將執行setmember方法。

1五、如何給UIbutton 同時設置圖片(Image)和文字(Title)以及它們的各類狀態? 

1 startRangeButton = [UIButton buttonWithType:UIButtonTypeCustom]; 2  startRangeButton.frame = CGRectMake(85,componentOriginY, regionImage.size.width, 16); 3 [startRangeButton setBackgroundImage:regionImage forState:UIControlStateNormal]; 4 //還能夠設置其高亮狀態startRangeButton setBackgroundImage:regionImage forState:UIControlStateHighlighted]; 
5  startRangeButton.titleLabel.font = [UIFont systemFontOfSize:7.0]; 6 [startRangeButton setTitle:@"2013-08-01 07:00" forState:UIControlStateNormal]; 7 [startRangeButton setTitleColor:COLOR(101, 199, 240, 1) forState:UIControlStateNormal]; 8 [startRangeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];  
View Code

代碼中我設置button背景圖片爲本身定義的一個regionImage,並設置了button的title = 「2013-08-01 07:00」【注意,設置了背景圖片後,title只能這樣添加,以button.titleLabel.text方式添加會沒法顯示的】,而且設置了tiitle正常和高亮下文字顏色。
因此看到這裏,應該明白button.setBackgroundImage 和 set Image 的區別了吧,前者是能夠同時設置文字,後者是一旦設置了image,沒法再顯示文字。

普通:高亮:  

1六、如何將NSDate類型轉化爲距離1970/1/1的毫秒差?   

 [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];  這種格式獲得的數值是精確到秒的,也就是說少1000,

可是嘗試[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];或SS大寫,或[formattersetDateFormat:@"yyyy-MM-dd HH:mm.ss.SSS"];都不起做用,最後才發現,

原來是這樣

NSTimeInterval自己是個秒級別的double類型數值,小數點後面即毫秒數,*1000.0f便可獲得毫秒級別的時間差 

1 //爲了兼容java版本,事件是從1970/1/1開始
 2 
 3 -(NSDate *)getDateTimeFromMilliSeconds:(long long) miliSeconds 5 { 7     NSTimeInterval tempMilli = miliSeconds; 8 
 9     NSTimeInterval seconds = tempMilli/1000.0; 10 
11     NSLog(@"seconds=%f",seconds); 12 
13     return [NSDate dateWithTimeIntervalSince1970:seconds]; 15 } 16 
17 
18 
19 //將NSDate類型的時間轉換爲NSInteger類型,從1970/1/1開始
20 
21 -(long long)getDateTimeTOMilliSeconds:(NSDate *)datetime 23 { 25     NSTimeInterval interval = [datetime timeIntervalSince1970]; 26 
27     NSLog(@"interval=%f",interval); 28 
29     long long totalMilliseconds = interval*1000 ; 30 
31     NSLog(@"totalMilliseconds=%llu",totalMilliseconds); 32 
33     return totalMilliseconds; 35 } 
View Code

也就是說,計算結果再本身乘以1000就能夠了

 1 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 2 [formatter setDateFormat:@"yyyy-MM-dd HH:mm"]; 3  
 4 NSDate *sDate  = [formatter dateFromString:startRangeButton.titleLabel.text]; 5 NSDate *eDate = [formatter dateFromString:endRangeButton.titleLabel.text]; 6 NSTimeInterval sinterval = [sDate timeIntervalSince1970]; 7 long long start = sinterval*1000; 8 NSTimeInterval einterval = [eDate timeIntervalSince1970]; 9 long long end = einterval*1000; 10 [mConnectionHelper doTrack:mobile startTime:start endTime:end];   
View Code 

1七、ios中的全局靜態變量  

Objective-C 支持全局變量
主要有兩種實現方式:
(1)第一種和C/C++中的同樣, 使用"extern"關鍵詞;
(2)另一種就是使用單例實現。
(好比咱們常常會把一個變量放在AppDelegate裏面做爲全局變量來訪問, 其中AppDelegate就是一個單例類)

在Objective-C中如何實現像C++中那樣的靜態成員變量呢?
你須要作的是在一個類A的implementation(.m或者.mm)文件中定義一個static變量,而後爲A類定義靜態成員函數(class method,也就是類方法)來操做該變量。  

1 //example.h 
2 @interface Example : NSObject { 3      
4 } 5 - (id)init; 6 +(int)instanceCount; 7 @end    

 1 //example.m 
 2  #import "example.h"           
 3 static int count; 4 @implementation Example 5 -(id)init{ 6     self = [super init]; 7     if(nil!=self){ 8         count+=1; 9 } 10  return self; 11 } 12 +(int)instanceCount{ 13      return count; 14 } 15 @end    
View Code

上面的例子中你就能夠經過[Example instanceCount]對靜態變量count進行訪問,無須建立實例。
警告:  static 寫在interface外面編譯是沒有錯誤的,可是編譯器會報警告,這麼說這樣的寫法是不被編輯器承認的。
錯誤:static 寫在interface裏面會直接報錯,顯然這樣的語法是不被承認的。

static關鍵字聲明的變量必須放在implementation外面,或者方法中,若是不爲它賦值默認爲0,
它只在程序開機初始化一次。

1八、如何使用 NSNotificationCenter 在viewcontroller之間進行傳值? 

簡單點的來,兩個界面間傳值,直接上代碼了:

sendViewcontroller.m  

 1 //SettingViewController :接受值的viewcontroller 
 2 SettingViewController *setting = [[SettingViewController alloc] init]; 3 [[NSNotificationCenter defaultCenter] addObserver:setting selector:@selector(received:) name:@"msetting" object:nil]; 4 NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"user",@"type", nil]; 5  
 6 [[NSNotificationCenter defaultCenter] postNotificationName:@"msetting" object:dict]; 7 [self.navigationController pushViewController:setting animated:YES]; 8  
 9 [setting release]; 10 SettingViewController.m(接收值的viewcontroller) 1 -(void)received:(NSNotification *)notification{ 2  
3     id data = [notification object]; 4     NSLog(@"received data: %@",data); 5 }  
View Code

這樣就實現了基本的使用,跟delegate相似,注意 addObserver時,須要寫目標viewcontroller的實例,而不是self。 

1九、Thread EXC_BAD_ACCESS : objc_retain, objc_getProperty 崩潰錯誤 



如上圖所示,遇到這個錯誤,從字面的意思咱們大體能猜到,是有屬性已經被release掉了,可是咱們又使用它了,因此,一部一部排查把,必定有某個地方的屬性

提早被release掉了,本身手動管理內存就會有這樣的困惱,代碼不少,不想去找,必定要有耐心,找的過程還能夠學到不少知識。


如上圖,這個就是我找到的緣由所在,unarchiver release掉了,而咱們在其它的類中想使用location的屬性。  

20、MAC 終端(bash)svn命令不識別 command not found   

在mac os 10.8中,svn Command line tools是沒有自動安裝的,這樣的話,svn 命令行就會失效,解決辦法:
1.打開xcode偏好設置(comand+,)-->"Download" -->Components:


2.點擊「Command line tools」下載,下載完成以後安裝。

3.安裝完成以後,打開終端,輸入「svn help」,若是出現以下所示,說明命令行工具安裝好了。

 2一、ios MapKit  判斷座標是否在MapView顯示範圍內    

1 CLLocationDegrees leftDegrees = mapView.region.center.longitude –(mapView.region.span.longitudeDelta / 2.0); 2 CLLocationDegrees rightDegrees = mapView.region.center.longitude +(mapView.region.span.longitudeDelta / 2.0); 3 CLLocationDegrees bottomDegrees = mapView.region.center.latitude –(mapView.region.span.latitudeDelta / 2.0); 4 CLLocationDegrees topDegrees = self.region.center.latitude +(mapView.region.span.latitudeDelta / 2.0); 5 if (leftDegrees > rightDegrees) { // Int'l Date Line in View 
 6 leftDegrees = -180.0 - leftDegrees; 7 if (coords.longitude > 0) // coords to West of Date Line 
 8 coords.longitude = -180.0 - coords.longitude; 9 } 10 If (leftDegrees <= coords.longitude && coords.longitude <= rightDegrees && bottomDegrees <= coords.latitude && coords.latitude <= topDegrees) { 11 // 座標在範圍內 
12 }   
View Code 

2二、在App圖標上顯示數字徽標

IOS7 : 

1  UIApplication *app = [UIApplication sharedApplication]; 2           
3  // 應用程序右上角數字 
4  app.applicationIconBadgeNumber = 99;   

上面的代碼能夠搞定 

IOS8:

iOS8中設置application badge value 會拋錯:Attempting to badge the application icon but haven't received permission from the user to badge the

緣由是由於在ios8中,設置應用的application badge value須要獲得用戶的許可。使用以下方法諮詢用戶是否許可應用設置application badge value

UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];

[[UIApplication sharedApplication] registerUserNotificationSettings:settings];

在這以前要判斷系統是否爲iOS8的系統,不然8以前的系統會報錯。

1  UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil]; 2           
3 [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; 4           
5  UIApplication *app = [UIApplication sharedApplication]; 6     // 應用程序右上角數字 
7     app.applicationIconBadgeNumber = 10;  
View Code

注意:清除數字請將數字設置爲 0

1-2設置標籤欄按鈕顯示數字圖標

1 UIViewController *second=[SecondViewController new]; 2 UITabBarItem *item=[[UITabBarItem alloc]initWithTitle:@"支付" image:[UIImage imageNamed:@"008"] selectedImage:[UIImage imageNamed:@"002"]]; 3     second.tabBarItem=item; 4     item.badgeValue=@"20";
View Code 

效果如圖

 

2三、如何獲取手機硬件信息?  

經過使用UIDevice: 

[[UIDevice currentDevice] systemName];
[[UIDevice currentDevice] systemVersion];//os version
[[UIDevice currentDevice] uniqueIdentifier];
[[UIDevice currentDevice] model];
[[UIDevice currentDevice] name];
真機上結果:
System Name: iPhone OS
System Version: 4.2.1
Unique ID: 9b5ded78d5fa0ac96250f8b4af0e46f40b96ea6d
Model: iPhone
Name: 「wwk」的 iPhone
模擬器上結果:
System Name: iPhone OS
System Version: 4.2
Unique ID: 21FFE0FF-429B-5D0B-96D2-EADCA3203260
Model: iPhone Simulator
Name: iPhone Simulator
uniqueIdentifier:iPhone經過,向幾個硬件標識符和設備序列號應用內部散列算法,而生成這一標識符。
http://blog.csdn.net/qiwancong/article/details/7914923 參考 

2四、設置隱藏頭部狀態欄(電池圖標)

1-1 設置狀態  如圖

1-2添加代碼:

1 //隱藏狀態欄
2 [[UIApplication sharedApplication]setStatusBarHidden:YES];

實現效果 如圖

2五、根據App版本號來判斷App開啓時是否進入引導頁 

實現代碼
 #define __kFirstVersion @"kFirstVersion"
 1 //根據App版本號來判斷App開啓時是否進入引導頁
 2 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 3        
 4     //1.獲取一個狀態:是否已經進入過主界面
 5 // BOOL b = [[[NSUserDefaults standardUserDefaults]valueForKey:__kFirst] boolValue];
 6     
 7     //獲取到當前的版本
 8     NSString *key = (NSString *)kCFBundleVersionKey; 9     NSString *version = [NSBundle mainBundle].infoDictionary[key]; 10     
11     //獲取到以前的版本
12     NSString *lastVersion = [[NSUserDefaults standardUserDefaults]valueForKey:__kFirstVersion]; 13     
14     //2.若是沒有進入過主界面,則進入引導頁
15     //若是兩個版本號相同,則進入主界面,不然進入引導頁
16     if (![lastVersion isEqualToString:version]) { 18         ViewController *vc = [[ViewController alloc]init]; 20         [vc setCallback:^{ 21 [self startApp]; 22 [[NSUserDefaults standardUserDefaults]setValue:version forKey:__kFirstVersion]; 23 [[NSUserDefaults standardUserDefaults]synchronize]; 24 }]; 26         self.window.rootViewController = vc; 27 } 28     //3.若是已經進入過主界面,則直接進入主界面
29     else
30 { 31 [self startApp]; 32 } 33     return YES; 34 } 35 
36 
37 -(void)startApp 38 { 39     self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[RootViewController new]]; 40 } 
View Code

2六、計算文本內容所佔空間大小方法

1)對於單行文本數據的顯示調用- (CGSize)sizeWithAttributes:(NSDictionary *)attrs;方法來獲得文本寬度和高度。

例如:

  //根據文本內容取得文本佔用空間大小
 CGSize textSize=[@"Hello World" sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15]}];

 2)對於多行文本數據的顯示調用- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context ;方法來獲得文本寬度和高度;同時注意在此以前須要設置文本控件的numberOfLines屬性爲0。  

 例如:
1 //計算多行文本所佔空間大小
2 CGSize textSize=[@"Hello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello World" boundingRectWithSize:CGSizeMake(100, MAXFLOAT) 3 options:NSStringDrawingUsesLineFragmentOrigin 4 attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15]} context:nil].size; 
View Code

 2七、圖解 imagView 的 UIContentMode的顯示方式 以下圖

 

2八、解決view的縮放的時候,layer.border.width(圓角邊框)隨着view的放大時會出現鋸齒化的問題。

   self.layer.allowsEdgeAntialiasing = YES;

2九、Xcode 7中http通訊出現以下錯誤:Application Transport Security has blocked a cleartext HTTP (http://)

   resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

緣由:

在iOS9 中,蘋果將原http協議改爲了https協議,使用 TLS1.2 SSL加密請求數據。

解決方法:

編輯 Info.plist,加入以下設置:NSAppTransportSecurity  ----> NSAllowsArbitraryLoads

如圖:

30、報錯: You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE)(解決方案)

解決方法有兩種:

方法一:使用Enable Bitcode的第三方庫

方法二:將工程中的Enable Bitcode設置爲NO 如圖:

 

3一、Xcode SVN  報錯 The server certificate failed to verify. 解決方法

打開終端(實用工具 -->終端),在終端中輸入以下命令:
svn ls https://xxxxxxxx/svn/xxxxxx   SVN的路徑
而後直接輸入 「 p 」  確認,再分別輸入電腦密碼、svn用戶名以及密碼;就能夠從新鏈接了。

3二、ios修改textField的placeholder的字體顏色、大小 方法

1 textField.placeholder = @"username is in here!"; 2 [textField setValue:[UIColor redColor]forKeyPath:@"_placeholderLabel.textColor"]; 3 [textField setValue:[UIFont boldSystemFontOfSize:16]forKeyPath:@"_placeholderLabel.font"];   
View Code

3三、iOS獲取當前根視圖控制器並實現頁面跳轉的方法

 1 - (UIViewController*)topViewController 2 { 3     return [self topViewControllerWithRootViewController:self.window.rootViewController]; 4 } 5 
 6 - (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController 7 { 8     if ([rootViewController isKindOfClass:[UITabBarController class]]) { 9         UITabBarController *tabBarController = (UITabBarController *)rootViewController; 10         return [self topViewControllerWithRootViewController:tabBarController.selectedViewController]; 11     } else if ([rootViewController isKindOfClass:[UINavigationController class]]) { 12         UINavigationController* navigationController = (UINavigationController*)rootViewController; 13         return [self topViewControllerWithRootViewController:navigationController.visibleViewController]; 14     } else if (rootViewController.presentedViewController) { 15         UIViewController* presentedViewController = rootViewController.presentedViewController; 16         return [self topViewControllerWithRootViewController:presentedViewController]; 17     } else { 18         return rootViewController; 19 } 20 } 21 
22 //調用
23 [[self topViewController] presentViewController:[[TransViewController alloc] init] animated:YES completion:nil]; 
View Code

 3四、全局變量宏定義實現方法  

1 #define APPDELEGATE ((AppDelegate *)[UIApplication sharedApplication].delegate)

 2 //用法:在AppDelegate.h中定義變量 經過 APPDELEGATE對象實現全局調用
 3 
 4 //AppDelegate.h 代碼
 5 #import <UIKit/UIKit.h> 
 6 @interface AppDelegate : UIResponder <UIApplicationDelegate> 
 7 @property (strong, nonatomic) UIWindow *window; 8 @property (strong,nonatomic) NSString *systemName; 9 @end
10 
11 //調用方法 (注意得引用頭文件 AppDelegate.h)
12  APPDELEGATE.systemName=@"KingKong";  
View Code

3五、解決MJExtension 轉換字段爲id(關鍵字)的問題處理

 1 #import "HGProductModel.h"
 2 #import "MJExtension.h"
 3 @implementation HGProductModel  4 
 5 //重寫 replacedKeyFromPropertyName 方法將id替換爲咱們定義的字段名
 6 + (NSDictionary *)replacedKeyFromPropertyName  7 {  8     return @{@"productID" : @"id"};  9 } 10 @end  
View Code

3六、tableviewcell上按鈕點擊時肯定當前所在行的方法

相似這種按鈕:

 1 -(void)btnClicked:(id)sender event:(id)event
 2 
 3 {  4 
 5   NSSet *touches =[event allTouches];  6 
 7   UITouch *touch =[touches anyObject];  8 
 9   CGPoint currentTouchPosition =[touch locationInView:self.tableView]; 10 
11   NSIndexPath *indexPath =[self.tableView indexPathForRowAtPoint:currentTouchPosition]; 12    
13    UITableViewCell *cell=[self tableView:tableView cellForRowAtIndexPath:indexPath]; 14 
15 }  
View Code

3七、設置UItableViewCell 右側小箭頭

  cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;

3八、UILabel 文字顯示刪除線方法 如圖:


1 NSString *bottomStr=[NSString stringWithFormat:@"原價%@",model.standardPrice]; 2 NSMutableAttributedString *attrString=[[NSMutableAttributedString alloc]initWithString:bottomStr]; 3 [attrString addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlinePatternSolid | NSUnderlineStyleSingle] 4 range:NSMakeRange(0, bottomStr.length)]; 5 self.bottomLb.attributedText=attrString; 
View Code

3九、xxx文件 is missing from working copy 解決方法

缺乏文件警告的Xcode 4

解決方案:
1.打開終端
2.cd 到警告所提示的文件夾下
3.執行命令svn rm --force 丟失文件的名稱
4.回車

5. find . -type d -name .svn | xargs rm -rf //該命令爲直接刪除指定文件夾下全部SVN相關
6. sudo find /Users/KingKong/Desktop/Scitel_Project/iOS-BigEvent/ -name ".svn" -exec rm -r {} \;//紅色字體爲項目路徑 

40、解決 UITableView 等UI控件下移的問題

1.//下方顯示不全 
_tableView.contentInset=UIEdgeInsetsMake(0, 0, -20, 0);   

2//其餘UI控件下移復位處理 
self.navigationController.navigationBar.translucent = NO;  

self.edgesForExtendedLayout = UIRectEdgeNone; 

self.automaticallyAdjustsScrollViewInsets = YES;

self.extendedLayoutIncludesOpaqueBars = YES;
View Code 

4一、UITableView 複用時實現修改FooterView背景色方法

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section { view.tintColor = HGTableViewBackColor; } 

4二、修改UIProgressView 高度的方法

CGAffineTransform transform = CGAffineTransformMakeScale(1.0f, 5.0f); self.progressView.transform = transform;

須要導入CoreGraphics.framework包

4三、根據index(下標)獲取TableViewCell 

1 NSIndexPath *indexPath =  [NSIndexPath indexPathForItem:i inSection:0]; 2 UITableViewCell *cell =  [self.tableView cellForRowAtIndexPath:indexPath]; 

4四、iOS 中 _OBJC_CLASS_$_xxxx 問題解決方案

錯誤代碼:

Undefined symbols for architecture x86_64:

  "_OBJC_CLASS_$_QQApiInterface", referenced from: 

      objc-class-ref in AppDelegate.o

  "_OBJC_CLASS_$_ShareSDK", referenced from:

      objc-class-ref in AppDelegate.o

      objc-class-ref in RecipeDetailViewController.o

      objc-class-ref in showViewController.o

      objc-class-ref in video_show.o

  "_OBJC_CLASS_$_TencentOAuth", referenced from:

      objc-class-ref in AppDelegate.o

  "_OBJC_CLASS_$_WXApi", referenced from:

      objc-class-ref in AppDelegate.o

  "_OBJC_CLASS_$_WeiboApi", referenced from:

      objc-class-ref in AppDelegate.o

  "_OBJC_CLASS_$_YXApi", referenced from:

      objc-class-ref in AppDelegate.o

ld: symbol(s) not found for architecture x86_64

clang: error: linker command failed with exit code 1 (use -v to see invocation) 

緣由:

   Xcode升級到6.1.1或以上版本後 默認讓全部App都經過64位編譯器編譯。原來在Xcode6.1.1如下版本的時候默認的

  Architectures只有(arm7,armv7s),到6.1.1或以上版本默認就帶上arm64的參數了。

方法:

1.把1.選中Targets—>Build Settings—>Combined--->Architectures。

把build active architectures only 改成 NO。

2. 把最下面的Valid Architectures中的arm64參數刪掉就能夠了

   或者:

雙擊Architectures,選擇other,刪除$(ARCH_STANDARD),而後增長armv7和armv7s(寫上:$(ARCHS_STANDARD_32_BIT))。

3.clean 再build。

設置好後效果圖:

 

4五、Xcode更新到7.3後會出現NSObject+MJProperty.h報Cannot create __weak reference in file using manual reference counting錯誤

解決的辦法:

在Build Settings---->Aplle LLVM7.1 - Language - Objectibe-C

---->Weak Reference In Manual Retain Release 設置爲YES

4六、清理Xcode中多餘的開發證書方法

即此處顯示的證書

進入此目錄 ~/Library/MobileDevice/Provisioning Profiles 刪除對應的證書便可。 

4七、解決no index path for table cell being reused 問題

 問題緣由是:我用nib自定義了一個cell。做爲個人tableHeaderView.固然在我執行下面的這段代碼的時候,tableHeaderView

 的顯示沒有任何問題。

headCell = [[NSBundle mainBundle] loadNibNamed:@"RRTableHeadBtnCell" owner:self options:nil][0]; self.tableView.tableHeaderView = headCell; 

可是:當我有數據須要更新cell的時候,當我要執行下面的代碼的時候,標題的error就出現了。並且個人tableFootView 也同時消失了。

 [self.tableview reloadSections:[NSIndexSet  indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];

問題是因爲將cell做爲section headerView 致使的題目所述錯誤。

解決方案其實很簡單:

 self.tableView.tableHeaderView = headCell.contentView;

4八、Xcode 打開項目一直顯示Indexing... 解決辦法 

Xcode用得久了,中類和方等字體顏色不提示,文件失去關聯,command+左鍵出現symbol not found。

 defaults write com.apple.dt.Xcode IDEIndexDisable 1   這能夠解決Xcode一直處於indexing狀態; 

  * 須要時候,把1改成0就能夠了:  defaults write com.apple.dt.Xcode IDEIndexDisable 0    這樣你的Xcode就

能夠正常代碼提示了   固然,這還有多是由於工程索引文件被破壞致使,可經過如下方法解決:

1)、Xcode -> Organizer -> Projects ->把全部工程中的Derived Data 刪除Delete掉。

2)、進入~/Library/Developer/Xcode/DerivedData 這個文件夾,把裏面相關工程的文件夾刪掉。

4九、iOS修改UIStatusBar 文字顏色方法

1)、在plist裏增長一行 UIStatusBarStyle(或者是「Status bar style」也能夠),這裏能夠設置兩個值,

 UIStatusBarStyleDefault (默認黑色)和 UIStatusBarStyleLightContent (白色),同時必須在plist中添加

View controller-based status bar appearance 設置NO; 此方法只對iOS7之後的操做有效。

50、 真機調試彈出 "Mac OS X"想要進行更改。鍵入管理員的名稱和密碼以容許執行此操做("Mac OS X"想使用系統鑰匙串)

解決方法:

打開鑰匙串訪問選擇系統下對應的證書點開雙擊,將訪問控制項改變到容許全部應用程序訪問此項目,輸入一次密碼便可,

之後就不會彈出了!

 

5一、Xcode8代碼出現輸出ubsystem: com.apple.UIKit, category: HIDEventFiltered, enable_level: 0 ...

解決辦法:【Product】-【Scheme】-【Edit Scheme】-【Run】-【Argument】-【Environment Variable】

添加keyValue【OS_ACTIVITY_MODE   disable】能夠中止輸出打印此日誌

 5二、實如今一個viewcontroller上加載另外一個viewcontroller方法

[self addChildViewController:otherVC];
[self.view addSubview:otherVC.view];

 5三、解決Xcode8 打開Xib文件後Xcode7 沒法打開並編譯的問題

 修改如上圖兩個地方便可。

5四、打包Framework中若是存在Category 形成在引用時崩潰的解決方法

在引用時須要在工程中的 Build Settings ----> other linker flags中添加 -ObjC 便可。

 

 

 >>>>>>>>>>第一部分<<<<<<<<<<<<

相關文章
相關標籤/搜索