閱讀446 返回首頁    go 阿裏雲 go 技術社區[雲棲]


《iOS6 application development》學習之路:No.4: 幾個coding中發現的小問題

不得不說 XCode是我用過的最好的IDE了,代碼自動補全、debug、真機調試都非常方便,可是就是因為功能很強大了,有一些細節上很容易出錯。記錄一下最近幾天編程中遇到的小問題:

1. 在寫第14章flowerColorTable程序時,發現程序完成之後,每次點擊一個條目是不會有反應的,而點擊其他條目的時候,彈出的對話框裏的內容是上次點擊的條目內容,後來經過好一番找,才找到問題所在。

原本的響應單元格選擇事件的函數是這樣的:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UIAlertView* showSelection;
    NSString* flowerMessage;
    
    switch (indexPath.section) {
        case kRedSection:
            flowerMessage = [[NSString alloc] initWithFormat:@"You Chose the red flower - %@", _redFlowers[indexPath.row]];
            break;
        case kBlueSection:
            flowerMessage = [[NSString alloc] initWithFormat:@"You Chose the blue flower - %@", _blueFlowers [indexPath.row]];
            break;
        default:
            flowerMessage = [[NSString alloc] initWithFormat:@"I have no idea what you chose"];
            break;
    }
    
    showSelection = [[UIAlertView alloc]
                     initWithTitle:@"Flower Selected" message:flowerMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [showSelection show];
}

但是因為XCode強大的自動補全功能,我直接默認的函數寫成了didDeSelectRowAtIndexPath,雖然就差2個字母,但是想必函數的意義也可以輕易地從字麵上區別出來了。

2. 設置一個背景按鈕,當用戶點擊鍵盤以外的區域是能夠自動隱藏鍵盤。

這個小技巧在第7章的時候就體會過了,意思是在用戶輸入框中需要輸入內容的時候,會彈出來鍵盤,用戶輸入完成之後,點擊鍵盤上的Done或者點擊鍵盤以外的區域都可以完成隱藏鍵盤的功能。這個功能的技巧是設置一個最下方的充滿整個屏幕的button,然後把button的點擊事件和退出鍵盤綁定在一起。

但是需要注意的是,一定要把鍵盤的模式設定成為Cutom,這樣它就會看不到,而不是把它隱藏了。同時如何把這個button放置到最底層呢?其實就是在大綱區域,把這個按鈕拖到最上部就行了,從上到下,控件一次是從後到前排列的。

3. 關於

NSDocumentDirectory和NSDocumentationDirectory

- (IBAction)storeSurvey:(id)sender {
    NSString* csvLine = [NSString stringWithFormat:@"%@,%@,%@\n",
                         self.firstName.text,
                         self.lastName.text,
                         self.emai.text];
    
    NSString* docDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString* surveyFile = [docDir stringByAppendingPathComponent:@"surveyresults.csv"];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:surveyFile]) {
        [[NSFileManager defaultManager]
         createFileAtPath:surveyFile contents:nil attributes:nil];
    }
    
    NSFileHandle* fileHandle = [NSFileHandle
                                fileHandleForUpdatingAtPath:surveyFile];
    [fileHandle seekToEndOfFile];
    [fileHandle writeData:[csvLine dataUsingEncoding:NSUTF8StringEncoding]];
    [fileHandle closeFile];
    
    self.firstName.text = @"";
    self.lastName.text = @"";
    self.emai.text = @"";
}
這段代碼是把內容存儲到程序的文件下麵的document目錄裏麵,但是剛開始的時候,我寫成了NSDocumentationDirectory這個函數,結果在想要輸出文件中內容的時候每次都找不到文件。後來google了一下這兩個函數的區別:

NSDocumentDirectory才是documents的路徑,NSDocumentationDirectory是Documentation的路徑。兩者是不一樣的。

最後更新:2017-04-03 06:03:03

  上一篇:go Swift類與結構體
  下一篇:go PHP的ip2long和long2ip函數的實現原理