gpt4 book ai didi

ios - 使用 SearchBar 时表格 View 单元格中的图像

转载 作者:行者123 更新时间:2023-11-28 21:19:10 24 4
gpt4 key购买 nike

我正在使用 Objective-C 在 Xcode 中开发一个应用程序。该应用程序有一个包含一系列餐厅的 TableView。我的问题是,当我尝试使用 SearchBar 时,我使用标题(餐厅名称作为过滤器),但是当我在过滤器搜索后显示行时,只有标题是正确的。单元格中的另一个标签和图像是错误的(它显示了正确的标题,但图像和另一个标签(描述标签)与原始表格 View 中的第一行相同)。

我必须更改我的 cellForRowAtIndexPath 方法,但我现在不知道如何更改它。

这是名为 MainTableViewController.h 的 TableViewController

#import <UIKit/UIKit.h>

@interface MainTableViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>

@property (weak, nonatomic) IBOutlet UIBarButtonItem *barButton;

//@property (nonatomic, strong) NSArray *Images;
//@property (nonatomic, strong) NSArray *Description;
//@property (nonatomic, strong) NSArray *Title;
@property (nonatomic, strong) NSMutableArray *Title;
@property (nonatomic, strong) NSMutableArray *Images;
@property (nonatomic, strong) NSMutableArray *Description;
@property (nonatomic, strong) NSMutableArray *filteredRest;
@property BOOL isFiltered;

@property (strong, nonatomic) IBOutlet UITableView *RestTableView;

@property (strong, nonatomic) IBOutlet UITableView *mySearchBar;

@end

这是我的 MainTableViewController.c

#import "MainTableViewController.h"
#import "SWRevealViewController.h"
#import "RestTableViewCell.h"
#import "RestViewController.h"

@interface MainTableViewController ()

@end

@implementation MainTableViewController

@synthesize mySearchBar, filteredRest, isFiltered;

- (void)viewDidLoad {
[super viewDidLoad];

_barButton.target = self.revealViewController;
_barButton.action = @selector(revealToggle:);

[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];

[self.navigationItem setTitle:@"MadEat"]; /*Cambia el titulo del navigation controller*/

[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}]; /*Cambia el color de las letras del navigation controller bar del menu principal*/

[self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:27/255.0f green:101/255.0f blue:163/255.0f alpha:1.0f]];

self.navigationController.navigationBar.tintColor = [UIColor whiteColor]; /*Cambia el color del boton de la izquierda*/

self.RestTableView.tableFooterView = [[UIView alloc] init]; /*Esta linea hace que en la tabla solo aparezcan el numero de filas que tienes establecidas, es decir, que las vacias no aparezcan*/

/*Alerta que se muestra solo la primera vez. Está desactivada*/
if (![@"1" isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"alert"]]) {
[[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"alert"];
[[NSUserDefaults standardUserDefaults] synchronize];

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Terms of use" message:@"The brands mentioned have no relationship with MadEat and the app has no any liability on that content." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:@"Accept" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];

[self presentViewController:alertController animated:YES completion:nil];
}

_Title = @[@"80 Grados",
@"90 Grados",
@"B&B Babel",
@"Babelia",
@"Bacira",
@"Bar Galleta",
@"Bar Tomate",
@"Barra Atlantica",
@"BaRRa de Pintxos",
@"BaRRa de Pintxos",];

_Description = @[@"Barrio Malasaña",
@"Barrio Retiro",
@"Barrio Chueca",
@"Barrio de Salamanca",
@"Barrio Chamberí",
@"Barrio Malasaña",
@"Barrio Chamberí",
@"Barrio Malasaña",
@"Barrio del Pilar",
@"Barrio Retiro",];

_Images = @[@"80_grados.png",
@"90_grados",
@"babel.png",
@"babelia.png",
@"bacira.png",
@"bar_galleta.png",
@"bar_tomate.png",
@"barra_atlantica.png",
@"barra_de_pintxos.png",
@"barra_de_pintxos.png",];
}

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

if (isFiltered == YES) {
return filteredRest.count;
} else {
return _Title.count;
}
}

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

// Configure the cell...
if (isFiltered == YES) {
cell.TitleLabel.text = [filteredRest objectAtIndex:indexPath.row];

} else {
int row = [indexPath row];
cell.TitleLabel.text = _Title[row];
cell.DescriptionLabel.text = _Description[row];
cell.RestImage.image = [UIImage imageNamed:_Images[row]];
}

cell.RestImage.layer.cornerRadius = 6;
cell.RestImage.clipsToBounds = YES;
cell.RestImage.layer.borderWidth = 1;

return cell;
}

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
/*Cambia el nombre del boton de la izquierda sin afectar al titulo del navigation controller*/
self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle: NSLocalizedString (@"Back", nil) style:UIBarButtonItemStylePlain target:nil action:nil];

if ([[segue identifier] isEqualToString:@"ShowDetails"]){
RestViewController *restviewcontroller = [segue destinationViewController];

NSIndexPath *myIndexPath = [self.tableView indexPathForSelectedRow];

int row = [myIndexPath row];
restviewcontroller.DetailModal = @[_Title[row],_Description[row],_Images[row]];

}
}

-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

if (searchText.length == 0) {
//Set our boolean flag
isFiltered = NO;
} else {
//Set our boolean flag
isFiltered = YES;
}
//Alloc and init our filteredData
filteredRest = [[NSMutableArray alloc] init];

for (NSString * restTitle in _Title) {
NSRange restTitleRange = [restTitle rangeOfString:searchText options:NSCaseInsensitiveSearch];

if (restTitleRange.location != NSNotFound) {
[filteredRest addObject:restTitle];
}
}

for (NSString * restDescription in _Description) {
NSRange restDescriptionRange = [restDescription rangeOfString:searchText options:NSCaseInsensitiveSearch];

if (restDescriptionRange.location != NSNotFound) {
//[filteredRest addObject:restDescription];
}
}

for (NSString * restImages in _Images) {
NSRange restImagesRange = [restImages rangeOfString:searchText options:NSCaseInsensitiveSearch];

if (restImagesRange.location != NSNotFound) {
//[filteredRest addObject:restImages];
}
}

//Reload our table view
[_RestTableView reloadData];
}

-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[mySearchBar resignFirstResponder];
}

@end

最后,这是我的名为 RestTableViewCell.h 的 TableViewCell.h

#import <UIKit/UIKit.h>

@interface RestTableViewCell : UITableViewCell

@property (strong, nonatomic) IBOutlet UILabel *TitleLabel;
@property (strong, nonatomic) IBOutlet UILabel *DescriptionLabel;
@property (strong, nonatomic) IBOutlet UIImageView *RestImage;

@end

这是我的图形问题:

The original TableView The problem filtering by Title

最佳答案

显然,您只是将过滤条件应用于 Title 数组,而不过滤 ImagesDescription 数组。

所以你需要另外两个 NSMutableArray 来保存 ImagesDescription 的过滤结果。

但我建议您为您的结果构建一个新的模型。示例代码供您引用:

模型层:Restaurant.h

@interface Restaurant : NSObject

@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *desc;
@property (nonatomic, copy) NSString *image;

- (instancetype)init:(NSString *)title descripiton:(NSString *)description image:(NSString *)image;

@end

餐厅.m

@implementation Restaurant

- (instancetype)init:(NSString *)title descripiton:(NSString *)description image:(NSString *)image {
self = [super init];
if (self != nil) {
self.title = title;
self.desc = description;
self.image = image;
}
return self;
}

@end

RestViewController.h

@interface RestViewController : UIViewController

@property (nonatomic, strong) Restaurant *DetailModal;

@end

MainTableViewController.m

@interface MainTableViewController ()

@property (nonatomic, strong) NSArray<Restaurant *> *originData;
@property (nonatomic, strong) NSMutableArray<Restaurant *> *filteredRest;
@property (nonatomic, assign) Boolean isFiltered;

@end

@implementation MainTableViewController

@synthesize mySearchBar, filteredRest, isFiltered, originData;

- (void)viewDidLoad {
[super viewDidLoad];

originData = @[
[[Restaurant alloc] init:@"80 Grados" descripiton:@"Barrio Malasaña" image:@"80_grados.png"],
[[Restaurant alloc] init:@"90 Grados" descripiton:@"Barrio Retiro" image:@"90_grados"]
];
filteredRest = [NSMutableArray new];
isFiltered = NO;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
//return _Title.count;

if (isFiltered == YES) {
return filteredRest.count;
} else {
return originData.count;
}
}

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

// Configure the cell...
if (isFiltered == YES) {
cell.TitleLabel.text = [filteredRest objectAtIndex:indexPath.row].title;
cell.DescriptionLabel.text = [filteredRest objectAtIndex:indexPath.row].desc;
cell.RestImage.image = [UIImage imageNamed:[filteredRest objectAtIndex:indexPath.row].image];
} else {
cell.TitleLabel.text = [originData objectAtIndex:indexPath.row].title;
cell.DescriptionLabel.text = [originData objectAtIndex:indexPath.row].desc;
cell.RestImage.image = [UIImage imageNamed:[originData objectAtIndex:indexPath.row].image];
}

cell.RestImage.layer.cornerRadius = 6;
cell.RestImage.clipsToBounds = YES;
cell.RestImage.layer.borderWidth = 1;

return cell;
}

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
/*Cambia el nombre del boton de la izquierda sin afectar al titulo del navigation controller*/
self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle: NSLocalizedString (@"Back", nil) style:UIBarButtonItemStylePlain target:nil action:nil];

if ([[segue identifier] isEqualToString:@"ShowDetails"]){
RestViewController *restviewcontroller = [segue destinationViewController];

NSIndexPath *myIndexPath = [self.tableView indexPathForSelectedRow];

if (isFiltered) {
restviewcontroller.DetailModal = filteredRest[myIndexPath.row];
} else {
restviewcontroller.DetailModal = originData[myIndexPath.row];
}
}
}

-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

if (searchText.length == 0) {
//Set our boolean flag
isFiltered = NO;
} else {
//Set our boolean flag
isFiltered = YES;
}
//Alloc and init our filteredData
filteredRest = [[NSMutableArray alloc] init];

for (Restaurant *item in originData) {
if ([item.title containsString:searchText]) {
[filteredRest addObject:item];
}
}

//Reload our table view
[self.tableView reloadData];
}

-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[mySearchBar resignFirstResponder];
}

@end

为你的信息建立一个新的model对象是非常有效的,所以你不需要对三个数组应用过滤器,你只需要搜索一次,结果将被保留在一个数组中。

PS:编写 OC 代码时,还有一个关于您的编码风格的提示,以小写字母命名变量、对象实例以及以大写字母命名类是最佳实践。例如,TitleLabel 应该重命名为 titleLabel,等等...

关于ios - 使用 SearchBar 时表格 View 单元格中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40444733/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com