gpt4 book ai didi

ios - 如何摆脱特定的 TableView 单元格

转载 作者:行者123 更新时间:2023-11-28 20:00:23 24 4
gpt4 key购买 nike

我的表格 View 中填充了显示商品及其名称、价格和品牌的单元格。我从 Web 服务返回的一些对象,在表格 View 单元格上看起来很难看。我不想填充价格为“空”的表格 View 单元格。到目前为止,这是我的代码。现在,我将其更改为“价格不可用”。

   for (NSDictionary *objItem in resultsArray)
{
NSString *currentItemName = [objectTitlesArray objectAtIndex:indexPath.row];

if ([currentItemName isEqualToString:objItem[@"title"]])
{
if (cell.priceLabel.text != (id)[NSNull null] && cell.priceLabel.text.length != 0 && cell.brandLabel.text != (id)[NSNull null] && cell.brandLabel.text.length != 0)
{


cell.nameLabel.text = currentItemName;

NSDictionary *bestPageDictionary = objItem[@"best_page"];

NSNumber *price = bestPageDictionary[@"price"];

if ((cell.priceLabel.text = @"<null>"))
{
cell.priceLabel.text = @"Price Unavailable";
}

else
{

cell.priceLabel.text = [NSString stringWithFormat:@"$%@", price];
}


NSArray *brandsArray = objItem[@"brands"];
cell.brandLabel.text = [brandsArray firstObject];
}

}
}

最佳答案

这是非常低效的。您将 JSON(我假设)保留在字典中,然后为您正在创建的每个单元格遍历字典。不仅如此,您没有提前清理 JSON。

创建一个无用的单元格然后返回并尝试删除它的代价要高得多。在您的 numberOfRowsInSection 委托(delegate)中,您已经告诉 tableview 您有 X 个单元格。现在您正在尝试删除会弄乱回调的单元格。您必须创建一个方法,该方法将在您完成创建所有单元格后运行,然后循环遍历所有单元格以将它们从 tableView 中删除,然后调用 [table reloadData]。但是,因为您实际上并没有从 NSDictionary 中删除数据,所以您实际上会再次创建相同数量的单元格并陷入无限循环。

解决方案:

首先,改变你的结构。获得 JSON 返回后,对其进行清理以删除所有没有价格的值。我还建议使用一个对象类来保存每个服务器对象。这将大大简化 TableView 以及其他类的代码。现在您已经清理了返回值,将其从 NSDictionary 更改为 NSMutableArray。然后在 numberOfRowsInSection: 中调用 [array count]。在 cellForRowAtIndexPath: 中,您只需查看 [array objectAtIndex:indexPath.row] 即可获取您的对象。

您通常希望代码看起来像这样:

ServerItem.h : NSObject{
@property (nonatomic,retain) NSString* name;
...
add in other properties here
}


- (NSMutableArray *) parseJSON:(NSDictionary *)jsonDict{
NSMutableArray *returnArray = [NSMutableArray array];
NSArray *dictArray = [NSArray arrayWithArray:jsonDict[@"results"]];
for (NSDictionary *itemDict in dictArray)
{
NSDictionary *bestPageDictionary = objItem[@"best_page"];
if (![bestPageDictionary[@"price"] isEqualToString:@"<null>"]])
{
ServerItem item = [ServerItem new];
item.price = ...
item.name = ....
[returnArray addObject:item];
}
}
return returnArray;
}

在您的网络服务代码中:

self.itemArray = [self parseJSON:dataDictionary];

然后

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.itemCallArray count]
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
ServerItem *cellItem = [self.itemsArray objectAtIndex:indexPath.row];
cell.nameLabel.text = cellItem.name;
cell.priceLabel.text = cellItem.price;
...

}

关于ios - 如何摆脱特定的 TableView 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24461904/

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