iOS UITableViewCells行被回收和标记不工作
我想寻求一些帮助在单元格中设置button的标签。 这是一个链接到我发布的前一个问题: iOS使用NSDictionary将数据加载到部分和行
但是,尽pipe我现在可以dynamic传递数据,但是每个行上的续订button似乎都无法获取数据,只有在select了该节中的任何行时,才会检测到每个节的相同书名。
根据我目前阅读的内容,这是因为button被回收,因此无法检测哪本书被正确select。 我试着设置标签:
cell.renewButton.tag = indexPath.row;
现在我的代码如何:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *CellIdentifier = @"Cell"; UserCustomCell *cell = (UserCustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; cell.bookTitle.frame = CGRectMake(12, 0, 550, 40); if (cell == nil) { [[NSBundle mainBundle] loadNibNamed:@"UserCustomCell" owner:self options:nil]; cell = userCustomCell; self.userCustomCell = nil; cell.renewButton.tag = indexPath.row; } if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { cell.bookTitle.frame = CGRectMake(12, 0, 550, 40); cell.renewButton.frame = CGRectMake(600, 14, 68, 24); } [cell.renewButton useBlackActionSheetStyle];
// ##########编辑从这里开始dataSource = [[NSMutableDictionary alloc] init]; //这将需要是一个伊娃
for (NSDictionary *rawItem in myArray) { NSString *date = [rawItem objectForKey:@"date"]; // Store in the dictionary using the data as the key NSMutableArray *section = [dataSource objectForKey:date]; // Grab the section that corresponds to the date if (!section) { // If there is no section then create one and add it to the dataSource section = [[NSMutableArray alloc] init]; [dataSource setObject:section forKey:date]; } [section addObject:rawItem]; // add your object } self.dataSource = dataSource; //NSLog(@"Data Source Dictionary: %@", dataSource); NSArray *sections =[[dataSource allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; NSString *sectionTitle = [sections objectAtIndex:indexPath.section]; NSArray *items = [dataSource objectForKey:sectionTitle]; NSDictionary *dict = [items objectAtIndex:indexPath.row]; cell.bookTitle.text = [dict objectForKey:@"name"]; cell.detail.text = [NSString stringWithFormat:@"Due Date: %@ Due Time: %@", [dict objectForKey:@"date"], [dict objectForKey:@"time"]]; cell.renewButton.tag = indexPath.row; return cell;
}
但它根本不起作用。 将sooooo感谢任何build议:)谢谢!
PS:我的xcode副本没有更新,只有版本4。 看到一些人提到在DataModel中存储标签状态,但只有在新版本中才可用。 🙂
我看不到你的cell.renewButton被分配了一个select器方法(应该在点击button时触发的方法)。
[cell.renewButton addTarget:self action:@selector(renewButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
另外,我会指定一个带有偏移量的标签号码,因为0的标签几乎就不是标签。 tableView的第一行将给indexPath.row = 0。
在你的代码上面,
#define OFFSET 100 /* Or any number greater than 0 */
在cellForRowAtIndexPath中,
... [cell.renewButton addTarget:self action:@selector(renewButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; cell.renewbutton.tag = indexPath.row + OFFSET; ...
在renewButtonPressed方法中,
-(void)renewButtonPressed:(id)sender { tappedNum = [sender tag] - OFFSET; /* do your stuff */ }
tappedNum会给你点击该button的行,从0开始。
您不能使用button标签,因为这些标签将与它们从中回收的单元格相同。 相反,使用indexPath
来确定你是哪一行,并直接使用它。 不需要通过button标签。