2012-08-30 55 views
1

我有一個numberOfSections ...方法,看起來像這樣:iOS版 - cellForRow ...如果邏輯

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 

    BOOL showContacts = self.selectedReminderMessageService != RMReminderMessageServiceTwitter ? YES : NO; 

    if (self.isEditing) { 

     if (showContacts) { 

      return 5; 

     } else { 

      return 4; 
     } 

    } else { 

     if (showContacts) { 

      return 4; 

     } else { 

      return 3; 
     } 
    } 
} 

我應該如何創建的cellForRowAtIndexPath ...方法?我是否必須列出所有可能的配置,例如:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    BOOL showContacts = self.selectedReminderMessageService != RMReminderMessageServiceTwitter ? YES : NO; 

    NSInteger section = [indexPath section]; 

    if (self.isEditing) { 
     if (showContacts) { 
       if (section == 0) { 
        // repeat to section 4 with else if's 
       } 
     } else { 
       if (section == 0) { 
        // repeat to section 3 else if's 
       } 
     } 
    } else { 
     if (showContacts) { 
       if (section == 0) { 
        // repeat to section 3 else if's 
       } 
     } else { 
       if (section == 0) { 
        // repeat to section 2 else if's 
       } 
     } 
    } 
} 

這可以以更有效的方式進行嗎?

+0

即嘗試在'if ... else ...'語句中使用'=='而不是'='運算符。 – holex

回答

0

所以這是當isEditing是真的,會出現一個附加部分,然後在出現的時候showContacts的附加部分是真的,如果各自的條件是錯誤的,這些部分就不會出現。我有這個權利嗎?那麼你的問題是如何使你的tableView:cellForRowAtIndexPath:方法中的數量少於if/else

這是我會做的:首先,總是返回相同數量的部分 - 在這種情況下,從numberOfSectionsInTableView。然後,在tableView:numberOfRowsInSection:中檢查條件,並在其爲false時返回0,如果爲true,則返回適當的行數。

現在,第0部分始終是您的「聯繫人」部分,第4部分總是「添加行」部分(或您希望放入的任何順序)。最後,在你的tableView:cellForRowAtIndexPath:方法中,你只需要檢查你所在的部分是否是正確的「類型」單元格。如果該部分中沒有行,那麼該位代碼將永遠不會被執行。

if (indexPath.section == 0) { 
    //contacts cell 
} else if (indexPath.section == 1) { 
    //cell for whatever section 1 is 
} else if (indexPath.section == 2) { 
    //etc. 
} //etc. 

如果你願意,你可以與伊斯梅爾的想法結合這個命名您的部分,雖然我從來沒有發現需要做多指示評論部分。

2

我有一個類似的問題,並最終創建一個枚舉數和一個給定indexPath(或節)的方法,返回它是什麼節。

這樣,無論何時您需要找到您在給定索引處處理的單元格類型(例如,單元格的創建和選擇),您只需要詢問該方法是什麼類型即可。

例如:

typedef enum { 
    SectionNone = 0, 
    SectionContacts, 
    SectionOptions, 
} Section; // do a more appropriate name 

- (Section)sectionForSection:(NSInteger)section { 
    // evaluate your state and return correct section 
} 

所以你cellForRow ......你可以去

Section sect = [self sectionForSection:indexPath.section]; 
switch (sect) { 
    case SectionContacts: { 
     // work with contact cell 
     break; 
    } 
    case SectionOptions: { 
     // work with options cell 
     break; 
    } 
    // etc 
} 
+0

我認爲如果您對模型的各個部分有不同的單詞,則會更容易理解。我使用了「組」這個詞。因此,我有一個'-groupForSection:'方法。我認爲它具有較少的充血性複雜性。 –

+0

我知道:)那就是爲什麼/ /做一個更合適的名稱。我發現這個特別有用的時候有動態部分 – Ismael