2015-08-31 27 views
0

我有一個表格視圖與左側檢查按鈕。前6個數據運行良好。當我添加三個更多的數據到我的表格視圖之後,當我檢查我的第一個數據時我的數據也得到檢查。像明智的,當我檢查一個數據的一些其他數據也對勾repeatng ..... 我使用的核心數據....如果任何人能回答這個問題......複選標記重複一些數據後添加....當我做檢查

@interface ViewController() 
{ 

    NSDateFormatter *formatter; 
} 

@property (strong) NSMutableArray *notes; 
@end 

@implementation ViewController 
@synthesize tableView; 
@synthesize addButton; 
@synthesize catefetchedResultsController; 


- (NSManagedObjectContext *)managedObjectContext { 
    NSManagedObjectContext *context = nil; 
    id delegate = [[UIApplication sharedApplication] delegate]; 
    if ([delegate performSelector:@selector(managedObjectContext)]) { 
     context = [delegate managedObjectContext]; 
    } 
    return context; 
} 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    self.navigationItem.title = @"My Notes"; 

    tableView.dataSource = self; 
    tableView.delegate = self; 
    [self.view addSubview:tableView]; 

    formatter = [[NSDateFormatter alloc] init]; 
    formatter.doesRelativeDateFormatting = YES; 
    formatter.locale = [NSLocale currentLocale]; 
    formatter.dateStyle = NSDateFormatterShortStyle; 
    formatter.timeStyle = NSDateFormatterNoStyle; 

      CATransition *animation = [CATransition animation]; 
      [animation setDuration:2.0]; 
      [animation setType:kCATransitionPush]; 
     [animation setSubtype:kCATransitionFromTop]; 

     [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]]; 

     [[addButton layer] addAnimation:animation forKey:@"SwitchToDown"]; 


} 

- (void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 

    // Fetch the devices from persistent data store 
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext]; 
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Notes"]; 

    NSError *error = nil; 
    self.notes = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy]; 

    NSSortDescriptor *titleSorter= [[NSSortDescriptor alloc] initWithKey:@"mod_time" ascending:NO]; 

    [self.notes sortUsingDescriptors:[NSArray arrayWithObject:titleSorter]] 
    ; 

    NSLog(@"Your Error - %@",error.description); 

    [tableView reloadData]; 
} 



#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    return 1; 
} 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // Return the number of rows in the section. 
    return self.notes.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    //UIButton *testButton; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 


     UIButton *testButton = [[UIButton alloc]initWithFrame:CGRectMake(5, 5, 40, 40)]; 


     [testButton setImage:[UIImage imageNamed:@"oval"] forState:UIControlStateNormal]; 

     [testButton setImage:[UIImage imageNamed:@"tick"] forState:UIControlStateSelected]; 

     [testButton addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside]; 

     [cell addSubview:testButton]; 
     [cell setIndentationLevel:1]; 
     [cell setIndentationWidth:45]; 





    cell.selectionStyle = UITableViewCellSelectionStyleNone; 

    } 


    // Configure the cell... 
     NSManagedObject *note = [self.notes objectAtIndex:indexPath.row]; 

     NSDate *date = [note valueForKey:@"mod_time"]; 

     NSString *dateString = [formatter stringFromDate:date]; 


     cell.textLabel.text = [note valueForKey:@"title"]; 



     cell.detailTextLabel.text = dateString; 




    return cell; 

} 

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    //cell.textLabel.font = [UIFont fontNamesForFamilyName:@"Avenir"]; 
    cell.textLabel.font = [UIFont fontWithName:@"Avenir" size:19.0]; 


    cell.detailTextLabel.font=[UIFont fontWithName:@"Avenir" size:15.0]; 

} 

-(void)buttonTouched:(id)sender 




{ 

     UIButton *btn = (UIButton *)sender; 

     if([[btn imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"oval"]]) 
     { 

      [btn setImage:[UIImage imageNamed:@"tick"] forState:UIControlStateNormal]; 

     } 
     else 
     { 
      [btn setImage:[UIImage imageNamed:@"oval"] forState:UIControlStateNormal]; 
        } 
    } 

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath]; 

     [tableView deselectRowAtIndexPath:indexPath animated:YES]; 


} 
- (IBAction)addButtonPressed:(id)sender { 
    AddNoteViewController *addNoteVC = [AddNoteViewController new]; 

    // to remove unused warning.... 
#pragma unused (addNoteVC) 

} 

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Return NO if you do not want the specified item to be editable. 
    return YES; 
} 

- (void)tableView:(UITableView *)cTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSManagedObjectContext *context = [self managedObjectContext]; 

    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     // Delete object from database 
     [context deleteObject:[self.notes objectAtIndex:indexPath.row]]; 

     NSError *error = nil; 
     if (![context save:&error]) { 
      NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]); 
      return; 
     } 

     // Remove device from table view 
     [self.notes removeObjectAtIndex:indexPath.row]; 
     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    } 
} 
- (IBAction)btnClick:(id)sender { 
} 
@end 

回答

1

好吧,我看到了你的代碼是問題的可重用性只是改變這一點,它會解決你的問題

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *CellIdentifier = @"cell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

//UIButton *testButton; 

    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 


    UIButton *testButton = [[UIButton alloc]initWithFrame:CGRectMake(5, 5, 40, 40)]; 


    [testButton setImage:[UIImage imageNamed:@"oval"] forState:UIControlStateNormal]; 

    [testButton setImage:[UIImage imageNamed:@"tick"] forState:UIControlStateSelected]; 

    [testButton addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside]; 

    [cell addSubview:testButton]; 
    [cell setIndentationLevel:1]; 
    [cell setIndentationWidth:45]; 





cell.selectionStyle = UITableViewCellSelectionStyleNone; 




// Configure the cell... 
    NSManagedObject *note = [self.notes objectAtIndex:indexPath.row]; 

    NSDate *date = [note valueForKey:@"mod_time"]; 

    NSString *dateString = [formatter stringFromDate:date]; 


    cell.textLabel.text = [note valueForKey:@"title"]; 



    cell.detailTextLabel.text = dateString; 




return cell; 

} 
+0

如何更新我的coredata提交,我需要保存我的複選標記? – david

+0

好吧,再創建一個問題,我會告訴你 –

0

由於細胞得到重用,你必須準備重用,或者你的按鈕在被另一行設置時顯示前一個圖像。

您必須重置按鈕的(選定)狀態以匹配當前行的狀態。

您可以在tableView:cellForRowAtIbdexPath:或單元格的prepareForReuse方法中執行此操作。

更新:

做到這一點的首選方法是繼承UITableViewCell,並添加一個UIButton屬性。這比向單元格(contentView,not)視圖添加按鈕要好得多。

在您的自定義單元格,它看起來像:

@interface ButtonCell : UITableViewCell 
{ 
    @property (weak) IBOutlet UIButton *toggleButton; 
} 

你可以在它的類扣式故事板的自定義單元格之間然後聯播IBOutlets和IBActions。

那麼它是一個簡單的事情,通過屬性來訪問您的單元中的按鈕:

[cell.toggleButton setImage:[UIImage imageNamed:@"oval"] forState:UIControlStateNormal]; 
[cell.toggleButton setImage:[UIImage imageNamed:@"tick"] forState:UIControlStateSelected]; 

如果各行應該開始與該圖像是一個橢圓形的是默認狀態,你會請確保調用從tableView:cellForRowAtIndexPath:

這些行這將覆蓋任何先前的切換狀態從其他行的單元格已被用於遺留下來的,所以你不會看到蜱當你想到一個橢圓:)

UPD吃了2:

既然你有一個自定義的單元格,你已經子類化,已經有一個按鈕,你不再需要創建或添加一個按鈕到單元格的(內容)視圖。所以,從舊的方法中,該代碼不再適用:

[cell addSubview:toogleButton]; // <-- remove this 

接下來,UITableViewCell沒有一個切換按鈕屬性。您需要使用您的子類別ButtonCell,其中具有toggleButton屬性。離開一個自定義單元格(您已經指定並連接到故事板的動態原型單元格中)。

ButtonCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath]; 

由於該方法總是返回一個單元格,可以消除所有的cell == nil條件代碼。

現在您已經有了一個自定義單元格,您可以設置它的圖像。

由於cellForIndexPath不是您切換其狀態的地方,因此您不希望有任何條件代碼在橢圓和刻度之間進行更改。

你現在的做法是試圖通過改變它顯示的圖像來讓按鈕跟蹤自己的勾號/橢圓狀態。 但單元格的按鈕將被重用,因爲單元格從屏幕上滾動出來。這意味着按鈕不能跟蹤其前一行是否被勾選。

無論何時您需要記住某行是否被勾選等事情時,您都希望在模型中(數組中)記錄此事。

因此,根據模型有條件地設置您的自定義按鈕的圖像。

if ([self.noteState objectAtIndex:indexPath.row]) // An array of flags indicating whether a row is checked or not 
    { 
     [cell.toggleButton setImage:[UIImage imageNamed:@"tick"] forState:UIControlStateSelected]; 
    } 
    else 
    { 
     [cell.toggleButton setImage:[UIImage imageNamed:@"oval"] forState:UIControlStateSelected]; 
    } 

現在您的表格行將被適當地關閉或不關閉。

由於您的模型已檢查狀態,因此您還需要更新buttonTouched代碼以類似地更新模型並切換按鈕。

我把它作爲一個練習。如果您在此之前已經瞭解了其他所有內容,那麼您將不會有任何應用所學內容的問題。

你的目標應該是學習和理解代碼塊的意圖,而不是簡單地從StackOverflow複製和粘貼它。

我明白,你想解決你正在開發的應用程序的問題,但除非你明白某件事情是如何或爲什麼起作用,否則你就會努力解決別人的代碼。

如果您有具體問題,請在評論中提問,我會盡力回答他們!

+0

我可以有一些例子PLZ? – david

+0

我已經添加了一個例子。如果您正在學習這一點,最好通過一些Apple的教程來解釋如何使用自定義單元格,並處理單元格重用問題。 tableViews不是太複雜,但你會很感激學習如何正確地編寫這樣的常見示例:) –

+0

感謝christian會檢查出這個...... – david

相關問題