ios-应用关闭后如何保存按钮状态?

时间:2015-12-15 18:52:18

标签: ios uitableview button nsuserdefaults

我奋斗了几天,然后搜查过。 我在UITableViewCell的按钮中找到了最喜欢的单元格。 应用程序关闭后如何保存按钮状态(选择按钮加载图像" fav.png"正常按钮加载" unfav.png")?

enter image description here

//  BirdsTableViewController.m
//  iranbirdtest2
//
//  Created by Mehdi on 9/27/15.
//  Copyright (c) 2015 Mehdi.n13. All rights reserved.
//  after 15 azar-21 mehr

#import "BirdsTableViewController.h"
#import "Bird.h"
#import "GeneralViewController.h"
#import "FavoriteTableViewController.h"
#import "MyManager.h"


//NSMutableArray *favoritesArray;
@interface BirdsTableViewController (){

}
@property (strong, nonatomic) UITabBarController *myTabbarController;
@property (strong, nonatomic) GeneralViewController *myFirstViewController;

@end

@implementation BirdsTableViewController
{

}

- (IBAction)buttonTouchDown:(UIButton *)sender {

sender.selected = !sender.selected; //to switch from selected to unselected 


//OR in IBaction we can use:


    /*
    if ([sender isSelected]) {
        [sender setImage:[UIImage imageNamed:@"unfav.png"] forState:UIControlStateNormal];
        [sender setSelected:NO];
    } else {
        [sender setImage:[UIImage imageNamed:@"fav.png"] forState:UIControlStateSelected];
        [sender setSelected:YES];
         [[NSUserDefaults standardUserDefaults] setBool:YES forKey: @"someKey"];
    }

     */

}

- (void) viewDidLoad {

    [super viewDidLoad];

    for (NSIndexPath *indexPath in [[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:@"mySavedMutableArray"]) {
        [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }


    self.title=@"پرندگان ایران";


    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //create array
    birds=[[NSMutableArray alloc]init];

    // UIButton* myButton;

    Bird *bird=[[Bird alloc]init];
    bird.name=@"زنبور خوار";
    bird.filename=@"bird1";
    bird.detail=@"این قسمت مربوط به توضیح می باشد";
    [birds addObject:bird];



    bird=[[Bird alloc]init];   //dont forget reuse
    bird.name=@"زاغ";
    bird.filename=@"bird2";
    bird.detail=@"توضیحات مربوط به شماره ۲";
    [birds addObject:bird];

    bird=[[Bird alloc]init];
    bird.name=@"طوطی";
    bird.filename=@"bird3";
    bird.detail=@"توضیحات مربوط به شماره سومی";
    [birds addObject:bird];


     //add more later




    MyManager *sharedManager = [MyManager sharedManager];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;




    //this is for page view controller:


    self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"common_bg"]];
    self.tableView.backgroundColor = [UIColor clearColor];



    UIEdgeInsets inset = UIEdgeInsetsMake(5, 0, 0, 0);
    self.tableView.contentInset = inset;
    [self.tableView setSeparatorStyle:UITableViewCellSelectionStyleNone];   //delete sepreate line odf tables


}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void) viewWillDisappear:(BOOL)animated{
}


#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 birds.count;
}


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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];



    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];


    }

    // Configure the cell...
    tableView.allowsSelection=YES;


    Bird *current=[birds objectAtIndex:indexPath.row];
    UIImageView *birdImageView = (UIImageView *)[cell.contentView viewWithTag:100];
    birdImageView.image = [UIImage imageNamed:current.filename];

    UILabel *name = (UILabel *)[cell.contentView viewWithTag:101];
    name.text=[current name];


    //button code in table view

    UIButton *button=(UIButton *) [cell.contentView viewWithTag:103];//fav
    [button setImage:[UIImage imageNamed:@"unfav.png"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"fav.png"] forState:UIControlStateSelected];
    button.frame = CGRectMake(0,0, 50, 50);
    button.tag = indexPath.row;
    [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:button]; // add the button to the cell
    [cell.contentView bringSubviewToFront:button];



    // Assign our own background image for the cell
    UIImage *background = [self cellBackgroundForRowAtIndexPath:indexPath];
    UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:background];
    cellBackgroundView.image = background;
    cell.backgroundView = cellBackgroundView;



    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sepratortable.png"]];
    [imgView sizeToFit];
    [cell.contentView addSubview:imgView];

    return cell;
}

-(void)buttonPressed:(UIButton *)sender
{

    NSLog(@"Button Pressed");
    MyManager *sharedManager = [MyManager sharedManager];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell*)sender.superview.superview];
    if([sharedManager.favoritesArray containsObject:[birds objectAtIndex:indexPath.row]])

    {
        [sharedManager.favoritesArray removeObject:[birds objectAtIndex:indexPath.row]];
        [self.tableView reloadData];
    }
    else
    {
        [sharedManager.favoritesArray addObject:[birds objectAtIndex:indexPath.row]];



        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Do you want to say hello?" message:@"More info..." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Say  Hello",nil];
        [alert show];

        ;  //we can remove later




    }
    //save favorite array in plist.
    [NSKeyedArchiver archiveRootObject:sharedManager.favoritesArray toFile:@"/Users/Mehdi/Desktop/Project/Backup/21 mehr/fav.plist"];


    NSLog(@"Favoritearray : %d",sharedManager.favoritesArray.count);


    /*
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setValue:birds forKey:@"key"];

    [[NSUserDefaults standardUserDefaults] synchronize];
    */



}


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


}

- (UIImage *)cellBackgroundForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger rowCount = [self tableView:[self tableView] numberOfRowsInSection:0];
    NSInteger rowIndex = indexPath.row;
    UIImage *background = nil;

    if (rowIndex == 0) {
        background = [UIImage imageNamed:@"cell_top.png"];
    } else if (rowIndex == rowCount - 1) {
        background = [UIImage imageNamed:@"cell_bottom.png"];
    } else {
        background = [UIImage imageNamed:@"cell_middle.png"];
    }

    return background;
}



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

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


#pragma mark - Navigation
/*



 In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 UITabBarController *pvc=[segue destinationViewController];
 // Pass the selected object to the new view controller.
 //what row selected?
 NSIndexPath *path=[self.tableView indexPathForSelectedRow];
 Bird *c  =birds[path.row];

 }
 */



- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    /* if ([segue.identifier isEqualToString:@"ShowGeneralView"]) {
     NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
     GeneralViewController *destViewController = segue.destinationViewController;
     destViewController.currentbird = [birds objectAtIndex:indexPath.row];
     }
     */
    self.myTabbarController = (UITabBarController*) [segue destinationViewController];
    self.myFirstViewController = [self.myTabbarController.viewControllers objectAtIndex:0];
    NSIndexPath *path=[self.tableView indexPathForSelectedRow];
    Bird *c  =birds[path.row];
    _myFirstViewController.currentbird=c;



}


@end

关闭应用程序后保存收藏行没有问题。 问题在于按钮状态无法保存和检索。

我知道我必须使用NSUserDefaults,但是如何使用?

1 个答案:

答案 0 :(得分:1)

好像您的收藏夹按钮位于单元格中,按下按钮时,您可以添加或删除鸟类阵列中的收藏夹。您甚至似乎在应用程序启动之间存储用于持久存储的文件的plist。除非我遗漏了某些内容,否则在构建行时需要在cellForRowAtIndexPath中设置按钮的状态。只需检查您正在构建的单元格的收藏夹数组,如果它在那里,请将图像设置为正确的状态。

需要注意的一点是,无论您认为图像的默认状态如何,都需要进行设置。这是因为细胞被重复使用(用于记忆效率)。因此,假设您使用灰色单元格的默认图像状态构建单元格。用户单击收藏夹图标,然后将其设置为红心。然后,当用户将单元格从屏幕滚动时,iOS将重复使用单元格,图像仍将设置为红色图像。如果你没有在你的收藏夹中没有明确地将它设置为灰色,那么它将保持红色。

另外,正如您在问题中提到的那样,您可以使用NSUserDefaults来存储您的收藏夹数组,而不是文件(它可能会更简单)。它还允许您使用iCloud跨设备同步用户收藏夹(有更多工作来处理合并冲突)。有很多资源可以在NSUserDefaults中存储数据。

在您的cellForRowAtIndexPath中,您可能希望执行以下操作:

   if([sharedManager.favoritesArray containsObject:[birds objectAtIndex:indexPath.row]])
{
    [button setSelected:NO];
} else {
    [button setSelected:YES];
}

另外,在buttonPressed方法中,您应该使用

切换按钮的选定状态
sender.selected = !sender.selected;

我将摆脱(IBAction)buttonTouchDown:方法并将所有按钮处理逻辑放在buttonPressed方法中。在两个地方拥有这种逻辑会引起混淆。