У меня есть UITableView с двумя разделами: бесплатный и оплаченный. Каждый раздел имеет различную ячейку. Свободные ячейки имеют две метки и изображение. Платные ячейки имеют две метки, изображение и кнопку, которые позволяют покупать продукт. После покупки продукта кнопка BUY на этой конкретной ячейке не должна отображаться снова. Говорит, что это как клетки инициализируются ...iOS: UITableView reloadData не работает
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *IDNormal = @"Normal";
static NSString *IDComplex = @"Complex";
if (indexPath.section == 0) { // show free objects
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:IDNormal];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:IDNormal] autorelease];
// product description
UILabel * labelDescription = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 54.0, 225, 18)];
[labelDescription setTextAlignment:UITextAlignmentLeft];
[labelDescription setBackgroundColor:[UIColor whiteColor ]];
[labelDescription setClipsToBounds:YES];
[labelDescription setFont:[UIFont systemFontOfSize:14.0]];
[labelDescription setTextColor:[UIColor blackColor]];
[labelDescription setAlpha:0.6];
[labelDescription setTag: 860];
[cell addSubview:labelDescription];
[labelDescription release];
// this will show the word FREE on free objects (cells)
UILabel * labelFREE = [[UILabel alloc] initWithFrame:CGRectMake(235.0, 54.0, 80, 18)];
[labelFREE setTextAlignment:UITextAlignmentCenter];
[labelFREE setBackgroundColor:[UIColor greenColor ]];
[labelFREE setClipsToBounds:YES];
[labelFREE setFont:[UIFont boldSystemFontOfSize:14.0]];
[labelFREE setTextColor:[UIColor blackColor]];
[labelFREE setAlpha:0.75];
[labelFREE setText:NSLocalizedString(@"freeKey", @"")];
[labelFREE setTag: 861];
[cell addSubview:labelFREE];
[labelFREE release];
}
cell.imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:[NSString stringWithFormat: @"free%d", indexPath.row] ofType:@"jpg"]];
NSString * prefixLabel = [NSString stringWithFormat: @"gratis%d", indexPath.row];
UILabel *labelDescription2 = (UILabel*)[cell viewWithTag:860];
[labelDescription2 setText:@"FREE"];
return cell;
} else { // show paid objects
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:IDComplex];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:IDComplex] autorelease];
UILabel * labelDescription = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 54.0, 225, 18)];
[labelDescription setTextAlignment:UITextAlignmentLeft];
[labelDescription setBackgroundColor:[UIColor whiteColor ]];
[labelDescription setClipsToBounds:YES];
[labelDescription setFont:[UIFont systemFontOfSize:14.0]];
[labelDescription setTextColor:[UIColor blackColor]];
[labelDescription setAlpha:0.6];
[labelDescription setTag: 1];
[cell addSubview:labelDescription];
[labelDescription release];
}
int numberPaidObject = indexPath.row + 500;
cell.imageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:[NSString stringWithFormat: @"table-pg%d", numberPaidObject] ofType:@"jpg"]];
NSString * nomeDoProduto = [NSString stringWithFormat: @"paid%d", numberPaidObject];
if (NotSoldProduct) {
NSString * prefixoEtiqueta = [NSString stringWithFormat: @"paid%d", numberPaidObject];
UILabel *labelDescription2 = (UILabel*)[cell viewWithTag:1];
[labelDescription2 setText:[description objectAtIndex: numberPaidObject ];
}
return cell;
}
}
, как я должен определить, какая BUY кнопка была нажата, и я использую dequeueReusableCellWithIdentifier, так что я должен использовать следующий метод ...
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
int numeroOfPaidObject = indexPath.row + 500;
if ((indexPath.section == 1) && ObjectForSale) {
// if paid objects and object was not bought yet
// in theory this section will not be executed if the object was already bought and paid
// so, I am skipping the BUY button creation and, in theory the cell will not have a BUY
// button… the problem is that it does...
UIButton * buyButton = [[UIButton alloc] initWithFrame:CGRectMake(235, 45, 80, 30)];
buyButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[buyButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
buyButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
buyButton.backgroundColor = [UIColor clearColor];
[buyButton addTarget:self action:@selector(buyNow:) forControlEvents:UIControlEventTouchDown];
[buyButton setTitle:NSLocalizedString(@"buyKey", @"") forState:UIControlStateNormal];
UIImage *newImage = [[UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource: @"whiteButton" ofType:@"png"]]
stretchableImageWithLeftCapWidth:12.0f topCapHeight:0.0f];
[buyButton setBackgroundImage:newImage forState:UIControlStateNormal];
[buyButton setTag: numeroOfPaidObject];
[cell addSubview:buyButton];
[buyButton release];
}
}
Проблема с этим кодом: когда я перезаряжаю данные таблицы, кнопка «ПОКУПАТЬ» продолжает отображаться на всех ячейках, включая те, которые уже были куплены пользователем.
Любые идеи?
благодарит за любую помощь.
это в теории, что эта строка «if ((indexPath.section == 1) && ObjectForSale)» означает, что кнопка отображается только в том случае, если объект продается (не приобретается) ... – SpaceDog
проблема в том, что кнопка не исчезает, когда ячейка перерабатывается. Когда он будет добавлен в иерархию представлений ячейки, он останется там до тех пор, пока вы явно не удалите его. На самом деле я готов поспорить, что многие из ваших ячеек имеют несколько кнопок, уложенных друг на друга. –
У меня были ситуации, когда я задал цвет текста красным в предложении 'if' и имел красный текст в ячейках, где код в' if' так и не был достигнут. После добавления строки 'else cell.textLabel.color = [UIColor blackColor] все работало, как ожидалось. –