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

标签 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,但是如何呢?

最佳答案

您的收藏夹按钮似乎位于一个单元格中,当按下该按钮时,您可以在鸟类数组中添加或删除收藏夹。您甚至似乎正在存储一个文件的 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 方法中。在两个地方使用该逻辑会导致困惑。

关于ios-应用程序关闭后如何保存按钮状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34297143/

相关文章:

ios - iOS 中的 GDAL,运行时 dll proj4 不可用,OGR 函数不起作用

ios - 让UIAccessibilityPostNotification在UIAlertView中完成

ios - Dateformatter 返回 nil 日期

iOS UITableView 在过滤时滚动插入

ios - 获取 customtableview 文本字段的 indexPath

image - Sitecore 营销人员模块的按钮图像

ios - layoutIfNeeded() 上的模糊崩溃

ios - UITableView.RectForHeaderInSection 导致 'Request for rect of invalid section' 异常,为什么?

android - 如何在 ExpandableListView 的组项中放置一个按钮?

vba - 如何在VBA中添加命令按钮?