发生事件时更改特定UITableViewCell的UIImage [英] Changing the UIImage of a specific UITableViewCell when an event occurs

查看:115
本文介绍了发生事件时更改特定UITableViewCell的UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 UITableViewController UITableView 中的一些静态单元格。 UITableView 正由另一个 UITableViewController prepareForSegue 。这个 UITableViewController 有两个部分,其中第一部分是字符串的 NSMutableArray ,第二部分是 NSMutableArray 包含带有字符串的.txt文件。一些语言将只有一个部分,其他人将有两个。对于 UITableView 没有其他想法。使用本教程:



一旦用户选择了星形图像,我就想在单元格上显示UIImage,表示此单元格已加星标。



以下是一些代码,以 cellForRowAtIndexPath

  static NSString * strCellIdentifier = @CustomLeafletVideoCell; 
CustomLeafletVideoTableViewCell * customCell =(CustomLeafletVideoTableViewCell *)[tableView dequeueReusableCellWithIdentifier:strCellIdentifier];

self.rightUtilityButton = [NSMutableArray new];

if(![[NSUserDefaults standardUserDefaults] boolForKey:@Favorite])
{
[self.rightUtilityButton sw_addUtilityButtonWithColor:
[UIColor colorWithRed:1.0f green :0.0f blue:0.0f alpha:1.0]
icon:[UIImage imageNamed:@Favorites@2x.png]];

}
else if([[NSUserDefaults standardUserDefaults] boolForKey:@Favorite])
{
[self.rightUtilityButton sw_addUtilityButtonWithColor:
[UIColor colorWithRed:1.0f green:0.0f blue:0.0f alpha:1.0]
icon:[UIImage imageNamed:@Database@2x.png]];


}

customCell.rightUtilityButtons = self.rightUtilityButton;
customCell.delegate = self;

当用户点击单元格中的图像时,此方法触发:

   - (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index 
{

switch索引){
case 0:
{

self.selectedRowCollection = [[NSMutableDictionary alloc] init];


NSIndexPath * indexPath = [self.tableView indexPathForCell:cell];

CustomLeafletVideoTableViewCell * cell =(CustomLeafletVideoTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];

//我们创建一个新的NSString并将其分配给自定义标签的文本(从cellForRow方法获得)
NSString * cellTitle = cell.customCellLabel.text;

NSLog(@文本是%@,cellTitle);


NSManagedObjectContext * context = [self managedObjectContext];

收藏夹* favorites = [NSEntityDescription insertNewObjectForEntityForName:@FavoritesinManagedObjectContext:context];
favourites.title = cellTitle;

NSError * error = nil;
if(![context save:& error])
{
//错误
}


[cell hideUtilityButtonsAnimated:YES ];


[self.tableView reloadData];
}
}

我在Core Data中存储了title。



问题



当我滑动单元格并按下星形图像不会在指定区域中使用 UIImageView 加载单元格。之所以不是因为我真的不明白该怎么办。



我理解答案是表明我应该创建一个自定义类,而我理解背后的理论,我不能理解如何实际实现这个。



我看过这个参考资料:使用NSMutableArray中的BOOL对象确定单元格状态以在选择单元格时使用复选标记作为附件。这工作,但它在第一部分和第二部分在相同的相应单元格上的复选标记。



我发现我可以从 indexPath.row 和<$获得确切的行号和节号c $ c> indexPath.section ,但我不知道如何处理这些信息。我可以随时为核心数据添加 isFavourite BOOL 模型,但是如何实际设置在 cellForRowAtIndexPath?



所以总结,我会提出这个问题,我需要了解如何:




  • 设置特定的 indexPath.row indexPath.section 与图片和

  • 保持它,以便每次我回到这 UITableViewController ,星号位于相应的储存格上



新手在这里,所以如果你乐意帮助尽可能多的信息,你可以,我真的很感激。



此外,我没有关于如何处理收藏夹的问题;工作 - 我只需要得到的图像到单元格时,一个单元格已标记为收藏。



任何指导将不胜感激。



更新



这是我设置收藏夹的代码: / p>

  self.isFavourite = @(!self.isFavourite.boolValue); 

其中 self.isFavourite 是<$在此 UITableViewController 上创建的c $ c> NSNumber 属性。



cellForRowAtIndexPath

  customCell.customCellLabel.text = [NSString stringWithFormat:@%@,[self.availableLeaflets objectAtIndex:indexPath.row]]; 
if(self.isFavourite.boolValue)
{
customCell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
customCell.accessoryType = UITableViewCellAccessoryNone;
}

这里的代码是从 .availableLeaflets 。这工作设置单元格上的复选标记,但问题是,当我回到这个 UITableViewController ,复选标记没有持续在选定的单元格。



这里, self.availableLeaflets 是一个 NSMutableArray UITableViewController 中的 prepareForSegue 中填充和设置。

解决方案

当用户点击一个单元格中的星形时,您的代码会将所有单元格标记为收藏,因为您在UserDefaults。



您必须单独存储每个单元格的收藏状态。每个单元格都必须有自己的favorite布尔值。



更新:



这是一个有关如何实现希望不使用Core Data。我为了清楚起见简化了示例:


  1. tableview显示单元格的标题。如果单元格是收藏,则会显示复选标记附件视图。

  2. 要标记单元格,您只需选择它。 (我省略了整个按钮代码保持示例简单)。如果您第二次选择单元格,它将从收藏夹中删除

这里是您需要做的:

  #importViewController.h
#import< CoreData / CoreData.h>
#importCellData.h
#importAppDelegate.h

@interface ViewController()< UITableViewDataSource,UITableViewDelegate>
@property(nonatomic)UITableView * tableView;
@property(nonatomic)NSMutableDictionary * favoritesDict;
@property(nonatomic)NSInteger上下文;
@property(nonatomic)NSString * language;
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

//设置表视图
self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
self.tableView.dataSource = self;
self.tableView.delegate = self;
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@Cell];
[self.view addSubview:self.tableView];

//在用户默认值中设置收藏字典(如果不存在)
if([[NSUserDefaults standardUserDefaults] valueForKey:@favoritesDict] == nil){
[[NSUserDefaults standardUserDefaults] setObject:@ {} forKey:@favoritesDict];
}

//设置当前表视图的语言
self.language = @en;

//从用户默认值加载收藏夹
self.favoritesDict = [[[NSUserDefaults standardUserDefaults] valueForKey:@favoritesDict] mutableCopy];

}

//此方法在给定索引路径更改单元格的收藏状态
- (void)toggleFavoriteStateForCellAtIndexPath:(NSIndexPath *)indexPath {

//切换单元格的最爱状态
NSString * key = [NSString stringWithFormat:@%@ _%ld_%ld,self.language,(long)indexPath.section, (long)indexPath.row];
if(self.favoritesDict [key] == nil){
self.favoritesDict [key] = @(1);
} else {
[self.favoritesDict removeObjectForKey:key];
}

//保存更改
[[NSUserDefaults standardUserDefaults] setObject:self.favoritesDict forKey:@favoritesDict];

//重载单元格
[self.tableView reloadRowsAtIndexPaths:@ [indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@CellforIndexPath :indexPath];

//将文本添加到单元格

//设置最喜欢的状态
NSString * key = [NSString stringWithFormat:@%@ _%ld_% ld,self.language,(long)indexPath.section,(long)indexPath.row];
if(self.favoritesDict [key]){
//显示收藏图像
cell.accessoryType = UITableViewCellAccessoryCheckmark; // for this example:show checkmark
} else {
//隐藏收藏的图片
cell.accessoryType = UITableViewCellAccessoryNone; //对于这个例子:hide checkmark
}

return cell;
}

#pragma mark - UITableViewDelegate

//在用户选择它时切换单元格的收藏状态
- (void)tableView: (UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[self toggleFavoriteStateForCellAtIndexPath:indexPath];
}

@end

多个部分。它使用NSDictionary并将偏好单元格存储在具有以下语法 LANGUAGE_SECTION_ROW 的键中。要检查单元格是否标记为收藏,只需检查字典中相关键是否有对象。该键的实际值并不重要。你只需检查钥匙。



只需确保您在 viewDidLoad 中设置语言字符串。


I have a simple UITableViewController with some static cells in the UITableView. The UITableView is being populated by another UITableViewController 's prepareForSegue. There are two sections to this UITableViewController, where the first section is a NSMutableArray of strings and the second section is a NSMutableArray containing a .txt file with strings. Some "languages" will only have one section and others will have two. There's nothing else fancy about the UITableView. With the use of this tutorial: http://www.appcoda.com/swipeable-uitableviewcell-tutorial/#disqus_thread, I have managed to implement custom gestures on the cell, so I can swipe the cell to mark it as favourite. I had to implement the use of the code in that tutorial to change the default behaviour from Delete to Star, as can be seen in the screenshot below:

Once a user has selected the star image, I want there to be UIImage on the cell itself, representing that this cell has been starred.

Here's some code, starting with the cellForRowAtIndexPath

static NSString *strCellIdentifier = @"CustomLeafletVideoCell";
CustomLeafletVideoTableViewCell *customCell = (CustomLeafletVideoTableViewCell *)[tableView dequeueReusableCellWithIdentifier:strCellIdentifier];

self.rightUtilityButton = [NSMutableArray new];

if (![[NSUserDefaults standardUserDefaults] boolForKey:@"Favourite"])
{
    [self.rightUtilityButton sw_addUtilityButtonWithColor:
     [UIColor colorWithRed:1.0f green:0.0f blue:0.0f alpha:1.0]
                                                 icon:[UIImage imageNamed:@"Favorites@2x.png"]];

}
else if ([[NSUserDefaults standardUserDefaults] boolForKey:@"Favourite"])
{
    [self.rightUtilityButton sw_addUtilityButtonWithColor:
     [UIColor colorWithRed:1.0f green:0.0f blue:0.0f alpha:1.0]
                                                 icon:[UIImage imageNamed:@"Database@2x.png"]];


}

customCell.rightUtilityButtons = self.rightUtilityButton;
customCell.delegate = self;

When the user taps the image in the cell, this method fires off:

- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index
{

    switch (index) {
        case 0:
        {

        self.selectedRowCollection = [[NSMutableDictionary alloc] init];


        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

        CustomLeafletVideoTableViewCell *cell = (CustomLeafletVideoTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];

        // We create a new NSString and assign it to the custom label's text (which is obtained from the cellForRow method)
        NSString *cellTitle = cell.customCellLabel.text;

        NSLog(@"The text is %@", cellTitle);


        NSManagedObjectContext *context = [self managedObjectContext];

        Favourites *favourites = [NSEntityDescription insertNewObjectForEntityForName:@"Favourites" inManagedObjectContext:context];
        favourites.title = cellTitle;

        NSError *error = nil;
        if (![context save:&error])
        {
            // Error
        }


        [cell hideUtilityButtonsAnimated:YES];


        [self.tableView reloadData];
    }
}

I am storing the "title" in Core Data.

Issue

When I swipe the cell and press the star image, it doesn't load up the cell with the UIImageView in the designated area. The reason it doesn't is because I truly don't understand what to do.

I understand the answer is indicating that I should create a custom class and while I understand the theory behind that, I cannot understand how to actually implement this appropriately.

I've looked at this reference: Using BOOL objects in NSMutableArray to determine cell statuses to use a checkmark as the accessory when a cell is selected. This works, but it places a checkmark in the first section and second section on the same corresponding cell.

I've figured out I can get the exact row number and section number from indexPath.row and indexPath.section, but I'm just not sure how to tackle this information at all. I could always add a isFavourite BOOL to the Core Data Model, but how do I actually set that in the cellForRowAtIndexPath?

So to conclude, and for the 250 bounty I'm putting on this question, I need to understand how:

  • Set the specific indexPath.row and indexPath.section with the image, and
  • Maintain it so that every time I come back to this UITableViewController, the star is on the appropriate cell

I'm kind of a newbie here, so if you're happy to help with as much information as you can, I'd really appreciate that.

Also, I'm not having issues with what to do with the Favourite after; that works - I just need to get the image onto the cell when a cell has been marked as favourite.

Any guidance would be appreciated.

Update

This is the code I have for setting the favourites:

        self.isFavourite = @(!self.isFavourite.boolValue);

Where self.isFavourite is a NSNumber property created on this UITableViewController.

In the cellForRowAtIndexPath:

    customCell.customCellLabel.text = [NSString stringWithFormat:@"%@",[self.availableLeaflets objectAtIndex:indexPath.row]];
    if (self.isFavourite.boolValue)
    {
        customCell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else
    {
        customCell.accessoryType = UITableViewCellAccessoryNone;
    }

The code here is setting the titles from the self.availableLeaflets. This works to set the checkmark on the cell, but the problem is, when I come back to this UITableViewController, the checkmark hasn't persisted on the selected cell.

Here, self.availableLeaflets is a NSMutableArray that gets populated and set from the prepareForSegue in the previous UITableViewController.

解决方案

Your code marks all cells as favorite when a user taps on the star in one cell because you store only 1 key in the UserDefaults.

You have to store the favorite state for each cell individually. Each cell must have its own 'favorite' boolean value.

Update:

This is a working example on how to achieve want you want without using Core Data. I simplified the example for clarity reasons:

  1. The tableview shows the title of the cell. If a cell is a favorite, it shows the checkmark accessory view.
  2. To mark a cell you simply select it. (I ommitted the whole button code the keep the example simple). If you select the cell a second time it is removed from the favorites

Here's what you have to do:

#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "CellData.h"
#import "AppDelegate.h"

@interface ViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSMutableDictionary *favoritesDict;
@property (nonatomic) NSInteger context;
@property (nonatomic) NSString *language;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // setup the table view
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    [self.view addSubview:self.tableView];

    // setup the favorites dictionary in user defaults (if it does not exist)
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"favoritesDict"] == nil) {
        [[NSUserDefaults standardUserDefaults] setObject:@{} forKey:@"favoritesDict"];
    }

    // set the language of your current table view
    self.language = @"en";

    // load favorites from user defaults
    self.favoritesDict = [[[NSUserDefaults standardUserDefaults] valueForKey:@"favoritesDict"] mutableCopy];

}

// this method changes the favorite state of the cell at a given index path
- (void)toggleFavoriteStateForCellAtIndexPath:(NSIndexPath *)indexPath {

    // toggle the favorite state of the cell
    NSString *key = [NSString stringWithFormat:@"%@_%ld_%ld", self.language, (long)indexPath.section, (long)indexPath.row];
    if (self.favoritesDict[key] == nil) {
        self.favoritesDict[key] = @(1);
    } else {
        [self.favoritesDict removeObjectForKey:key];
    }

    // save the change
    [[NSUserDefaults standardUserDefaults] setObject:self.favoritesDict forKey:@"favoritesDict"];

    // reload the cell
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10;
}

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

    // add the text to your cell

    // set up favorite state
    NSString *key = [NSString stringWithFormat:@"%@_%ld_%ld", self.language, (long)indexPath.section, (long)indexPath.row];
    if (self.favoritesDict[key]) {
        // show the favorite image
        cell.accessoryType = UITableViewCellAccessoryCheckmark; // for this example: show checkmark
    } else {
        // hide the favorite image
        cell.accessoryType = UITableViewCellAccessoryNone; // for this example: hide checkmark
    }

    return cell;
}

#pragma mark - UITableViewDelegate

// toggle the favorite state of the cell when the user selects it
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self toggleFavoriteStateForCellAtIndexPath:indexPath];
}

@end

This example works for tables with multiple sections. It uses a NSDictionary and stores favorited cells in a key that has the following syntax LANGUAGE_SECTION_ROW. To check if a cell is marked as favorite just check if there is a object for the related key in the dictionary. The actual value of that key does not matter. You just check for the key.

Just make sure that you set the language string in viewDidLoad.

这篇关于发生事件时更改特定UITableViewCell的UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆