2012-02-24 70 views
12

我剛剛開始爲iPhone編程,我正在創建一個連接到數據庫並獲取一組行名稱並顯示它們的應用程序。選中後,行的背景顏色會發生變化,即您可以進行多項選擇,並且它們都將是不同的顏色。所以我從服務器上取回XML沒有問題,我創建了一個UITableView來顯示單元格。但是,我不知道如何將單元格添加到表格中。我看過insertRowsAtIndexPaths,但我不確定如何使用它?據我所知,insertRowsAtIndexPaths需要兩個參數:以編程方式向UITableView添加單元格

一個NSArray,它包含單元格應該在哪一行以及哪一部分。這個問題是我的應用程序將有一個動態的行數。如果我不知道有多少行,我將如何去創建NSArray?我可以使用NSMutableArray嗎?

它需要的第二個參數是一個動畫 - 這非常簡單。

我遇到的另一個問題是我在哪裏創建單元格?你如何將單元格傳遞給tableview?

我試過閱讀文檔,但它似乎不太清楚!這是在視圖控制器的loadView方法中的那一刻我的代碼有:

//Before this I get the XML from the server so I am ready to populate 
//cells and add them to the table view 
NSArray *cells = [NSArray arrayWithObjects: 
        [NSIndexPath indexPathForRow:0 inSection:0], 
        [NSIndexPath indexPathForRow:1 inSection:0], 
        [NSIndexPath indexPathForRow:2 inSection:0], 
        [NSIndexPath indexPathForRow:3 inSection:0], 
        [NSIndexPath indexPathForRow:4 inSection:0], 
        [NSIndexPath indexPathForRow:5 inSection:0], 
        [NSIndexPath indexPathForRow:6 inSection:0], 
        [NSIndexPath indexPathForRow:7 inSection:0], 
        [NSIndexPath indexPathForRow:8 inSection:0], 
        [NSIndexPath indexPathForRow:9 inSection:0], 
        [NSIndexPath indexPathForRow:10 inSection:0], 
        [NSIndexPath indexPathForRow:11 inSection:0], 
        [NSIndexPath indexPathForRow:12 inSection:0], 
        nil]; 
[eventTypesTable beginUpdates]; 
[eventTypesTable insertRowsAtIndexPaths:cells withRowAnimation:UITableViewRowAnimationNone]; 
[eventTypesTable endUpdates]; 

回答

18

我認爲你從錯誤的方向接近這一點。 UITableViews不能按照您的預期工作。 insertRowsAtIndexPaths用於將新行插入到表中,而不是在第一個實例中填充它。

UITableViews通過調用一些委託方法來工作,這些委託方法允許您根據需要將數據呈現到表視圖。該框架然後負責繁重的填充來填充單元格,處理滾動和觸摸事件等。

我建議您先閱讀如下所示的教程:http://www.iosdevnotes.com/2011/10/uitableview-tutorial/,這對我來說看起來相當透徹。它解釋瞭如何爲表格設置數據源以及如何配置數據由UITableView呈現的方式。

祝你好運!

+0

謝謝,我知道我完全搞不清怎麼奏效。我已經設法正確輸出這些單元格,但是我遇到了問題。我從數據庫檢索12行,但屏幕只適合7.一旦屏幕已滿,並在模擬器,如果我試着向下滾動我得到一個錯誤'NSString * sEventType = [[eventTypes valueForKeyPath:@「name .text「] objectAtIndex:indexPath.row];'cellForRowAtIndexPath'方法內部。有什麼我失蹤?像我必須添加一個滾動控制器或什麼?再一次感謝您的及時和有益的迴應! – KerrM 2012-02-24 12:37:44

+7

鏈接已損壞。這就是爲什麼你至少應該發佈一些示例代碼而不是依靠外部鏈接。 – 2014-02-28 19:16:38

+0

鏈接已損壞,但您可以在此處找到此網址的內容:http://web.archive.org/web/20150928131750/http://www.iosdevnotes.com/2011/10/uitableview-tutorial/ – Upsilon42 2016-05-04 13:35:49

16

不需要使用insertRowsAtIndexPaths

檢查:UITableViewDataSource Protocol ReferenceUITableView Class Reference

,奇蹟發生了這三種方法(UITableViewDataSource協議方法)之間:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; 

你只需要填寫一個數組。是的,它可以是NSMutableArray

您可以填寫在陣列中- (void)viewDidLoad,例如:

yourItemsArray = [[NSMutableArray alloc] initWithObjects:@"item 01", @"item 02", @"item 03", nil]; 

而且他們使用的數據源的方法是這樣的:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    // If You have only one(1) section, return 1, otherwise you must handle sections 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // Return the number of rows in the section. 
    return [yourItemsArray count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    } 

    // Configure the cell... 
    cell.textLabel.text = [NSString stringWithFormat:[yourItemsArray objectAtIndex:indexPath.row]]; 

    return cell; 
} 

像這種細胞將被自動創建。

如果您恰克陣列,只需要調用:

[self.tableView reloadData]; 
+0

謝謝爲了您的回覆,我希望我可以選擇多個答案作爲可接受的答案。 – KerrM 2012-02-24 12:38:17

+3

沒關係,對同一個問題有不同的方法。如果你開始學習,你應該通過教程來了解事情的工作方式,而不僅僅是代碼。但這兩個真的有幫助 – Frade 2012-02-24 12:44:45

+0

是的,我想象會有。我遇到了另一個問題,但我希望你能幫助 - 我從數據庫中檢索12行,但屏幕只適合7.一旦屏幕已滿並且在模擬器中,如果我嘗試向下滾動,則獲取NSString * sEventType = [[eventTypes valueForKeyPath:@「name.text」] objectAtIndex:indexPath.row];在cellForRowAtIndexPath方法中。這幾乎就像一旦它到達屏幕的底部,該方法就會停止運行。這是我做錯了什麼嗎? – KerrM 2012-02-24 12:51:25

2
//######## Adding new section programmatically to UITableView ############ 

    @interface MyViewController : UIViewController<UITableViewDataSource,UITableViewDelegate> 
    { 
     IBOutlet UITableView *tblView; 
     int noOfSection; 
    } 
    -(IBAction)switchStateChanged:(id)sender; 
    @end 



    @implementation MyViewController 
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{ 
     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
     if (self) { 
      // Custom initialization 
     } 
     return self; 
    } 
    - (void)viewDidLoad{ 
     [super viewDidLoad]; 

     noOfSection = 2; 
    } 
    - (void)viewDidUnload{ 
     [super viewDidUnload]; 
    } 
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{ 
     if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { 

      return YES; 
     } 

     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); 
    } 
    #pragma mark - TableView Delegate Methods 
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 
     return noOfSection; 
    } 
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 

     return 1; 
    } 
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 
     if(indexPath.section == 2){ 
      return 200; 
     } 
     return 50; 
    } 

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

     static NSString *CellIdentifier = @"Cell"; 

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if (cell == nil) { 
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 

      UISwitch *switchBtn = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 20, 10)]; 
      cell.accessoryView = switchBtn; 

      [switchBtn addTarget:self action:@selector(switchStateChanged:) forControlEvents:UIControlEventValueChanged]; 
      cell.textLabel.font = [UIFont systemFontOfSize:14]; 
      cell.detailTextLabel.font = [UIFont systemFontOfSize:11]; 
      cell.textLabel.numberOfLines = 2; 
      cell.detailTextLabel.numberOfLines = 2; 
     } 



     if(indexPath.section == 0){ 
      cell.textLabel.text = @"Cell-1 Text"; 
      cell.detailTextLabel.text = @"Cell-1 Detail text"; 
     } 
     else if(indexPath.section == 1){ 
      cell.textLabel.text = @"Cell-2 Text"; 
     } 
     else { // new added section code is here... 
      cell.textLabel.text = @"New Added section"; 
     } 
     [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; 
     return cell; 
    } 
    -(IBAction)switchStateChanged:(id)sender{ 
     UISwitch *switchState = sender; 

     if(switchState.isOn == YES){ 
      NSLog(@"ON"); 
      NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:2]; 
      [self insertNewSectionWithIndexPath:indexPath]; 
     } 
     else { 
      NSLog(@"OFF"); 
      [self removeSectionWithIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]]; 
     } 
    } 
    -(void)insertNewSectionWithIndexPath:(NSIndexPath *)indexPath{ 


     noOfSection = 3; 
     [tblView insertSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationFade]; 
    } 
    -(void)removeSectionWithIndexPath:(NSIndexPath *)indexPath{ 
     noOfSection = 2; 
     [tblView deleteSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationFade]; 
    } 
    @end 
相關問題