2012-02-24 38 views
12

Tôi vừa mới bắt đầu lập trình cho iPhone và tôi đang tạo một ứng dụng kết nối với cơ sở dữ liệu và nhận một bộ tên hàng và hiển thị chúng. Khi được chọn, màu nền của hàng thay đổi tức là bạn có thể thực hiện nhiều lựa chọn và tất cả chúng sẽ có màu khác nhau. Vì vậy, tôi nhận được XML trở lại từ máy chủ không có vấn đề và tôi đã tạo ra một UITableView để hiển thị các tế bào in Tuy nhiên, tôi không có ý tưởng làm thế nào để thêm các tế bào vào bảng. Tôi đã xem insertRowsAtIndexPaths nhưng tôi không biết cách sử dụng? Theo tôi hiểu, insertRowsAtIndexPaths có hai tham số:Thêm ô theo lập trình vào UITableView

NSArray chứa hàng nào được cho là ô và trong phần nào. Vấn đề với điều này là ứng dụng của tôi sẽ có số hàng động. Làm thế nào tôi sẽ đi về việc tạo ra NSArray nếu tôi không biết có bao nhiêu hàng tôi sẽ có? Tôi có thể sử dụng NSMutableArray không?

Tham số thứ hai cần có là hoạt ảnh - điều này khá đơn giản.

Một vấn đề khác mà tôi đang gặp phải là tôi thực sự tạo các ô ở đâu? Làm thế nào để bạn vượt qua các tế bào để tableview?

Tôi đã thử đọc tài liệu nhưng dường như không rõ ràng lắm! Dưới đây là đoạn code tôi có ít thời điểm bên trong phương pháp loadview của bộ điều khiển xem:

//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]; 

Trả lời

18

Tôi nghĩ rằng bạn sắp sửa bước sang này từ sai hướng. UITableViews không hoạt động như bạn mong đợi. insertRowsAtIndexPaths là để chèn các hàng mới vào một bảng, thay vì để điền vào nó trong trường hợp đầu tiên.

Công cụ UITableViews hoạt động bằng cách gọi một số phương thức ủy quyền cho phép bạn trình bày dữ liệu của mình vào chế độ xem bảng khi cần. Sau đó, khung công tác sẽ chăm sóc việc nâng vật nặng lên các ô, xử lý các sự kiện cuộn và chạm, v.v.

Tôi khuyên bạn nên bắt đầu bằng cách đọc hướng dẫn như thế này: http://www.iosdevnotes.com/2011/10/uitableview-tutorial/, trông khá kỹ lưỡng đối với tôi. Nó giải thích cách thiết lập nguồn dữ liệu của bạn cho bảng và cách bạn có thể cấu hình cách dữ liệu của bạn được trình bày bởi UITableView.

Chúc may mắn!

+0

Cảm ơn, tôi thấy tôi đã hoàn toàn nhầm lẫn về cách mà làm việc. Tôi đã quản lý để đầu ra các tế bào một cách chính xác bây giờ nhưng tôi nhận được một vấn đề. Tôi đang lấy 12 hàng từ cơ sở dữ liệu tuy nhiên, màn hình chỉ phù hợp 7. Khi màn hình đầy và trong trình mô phỏng nếu tôi cố gắng cuộn xuống, tôi gặp lỗi trong 'NSString * sEventType = [[eventTypes valueForKeyPath: @" name .text "] objectAtIndex: indexPath.row];' bên trong phương thức 'cellForRowAtIndexPath'. Có điều gì tôi đang thiếu? Giống như tôi phải thêm một bộ điều khiển cuộn hay gì đó? Một lần nữa, cảm ơn phản hồi nhanh chóng và hữu ích! – KerrM

+7

Liên kết bị hỏng. Đây là lý do tại sao bạn nên đăng ít nhất một số mã mẫu thay vì dựa vào các liên kết bên ngoài. Liên kết –

+0

bị hỏng nhưng bạn có thể tìm thấy nội dung của url này tại đây: http://web.archive.org/web/20150928131750/http://www.iosdevnotes.com/2011/10/uitableview-tutorial/ – Upsilon42

16

Không cần sử dụng insertRowsAtIndexPaths.

Kiểm tra: UITableViewDataSource Protocol ReferenceUITableView Class Reference

Sự kỳ diệu sẽ xảy ra giữa ba phương pháp này (phương pháp giao thức UITableViewDataSource):

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

Bạn chỉ cần điền vào một mảng. Có, nó có thể là NSMutableArray.

Bạn có thể điền mảng trong - (void)viewDidLoad, ví dụ:

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

Và họ sử dụng các phương pháp nguồn dữ liệu như thế này:

- (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; 
} 

Giống như các tế bào này sẽ được tạo ra tự động.

Nếu Bạn chage Array, chỉ cần gọi:

[self.tableView reloadData]; 
+0

Cảm ơn cho câu trả lời của bạn, tôi ước tôi có thể chọn nhiều câu trả lời như một câu trả lời được chấp nhận. – KerrM

+3

OK, có nhiều cách tiếp cận khác nhau cho cùng một vấn đề. Và nếu bạn bắt đầu học, bạn nên thực hiện các hướng dẫn để hiểu cách mọi thứ hoạt động, không chỉ là mã. Nhưng cả hai thực sự giúp đỡ – Frade

+0

Có tôi tưởng tượng sẽ có. Mặc dù vậy, tôi đã gặp phải một vấn đề khác, tôi hy vọng bạn có thể giúp - Tôi đang lấy 12 hàng từ cơ sở dữ liệu, màn hình chỉ vừa với 7. Khi màn hình đầy và trong trình mô phỏng nếu tôi cố gắng cuộn xuống lỗi trong NSString * sEventType = [[eventTypes valueForKeyPath: @ "name.text"] objectAtIndex: indexPath.row]; bên trong phương thức cellForRowAtIndexPath. Nó gần giống như phương pháp đó sẽ ngừng chạy một khi nó được vào dưới cùng của màn hình. Đây có phải là điều tôi đã làm sai không? – KerrM

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 
Các vấn đề liên quan