我对内容视图有两个问题。
第一个问题: tableview单元格中有两个内容视图。我如何知道哪一个被触及?
第二个问题: 我只希望内容视图出现在tableview的第一部分。 但是,当我向上滚动tableview时,内容视图也出现在第三部分中。 我该如何解决这个问题?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIImageView *imgView, *imgView1;
if(cell == nil)
{
if (indexPath.section == 0) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.text = @"test";
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(100,0,20,62)];
[imgView setImage:[UIImage imageNamed:@"1.png"]];
imgView.tag = 10;
[cell.contentView addSubview:imgView];
[imgView release];
imgView1 = [[UIImageView alloc] initWithFrame:CGRectMake(200,0,20,62)];
[imgView1 setImage:[UIImage imageNamed:@"2.png"]];
imgView1.tag = 20;
[cell.contentView addSubview:imgView1];
[imgView1 release];
}
}
else
{
if (indexPath.section == 0) {
imgView = (id)[cell.contentView viewWithTag:10];
imgView1 = (id)[cell.contentView viewWithTag:20];
}
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
// How do I know left content view is touched or right content view is touched?
}
答案 0 :(得分:0)
1)您可以为每个视图添加不同的识别器,这些识别器将调用不同的方法。
// create view
UIImageView *view = [UIImageView ...];
view.userInteractionEnabled = YES;
// create recognizer
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myViewTapped:)];
// add recognizer to your view
[view addGestureRecognizer:recognizer];
[recognizer release];
// now when user will tap on your view method - (IBAction)myViewTapped:(UIGestureRecognizer); will be called
2)当您重复使用单元格时,不要忘记在内容视图中删除或删除不必要的视图(因为它们已在前一部分中添加并在第三部分中重复使用)。
UIView *view2remove = [cell viewWithTag:itsTag];
[view2remove removeFromSuperview];
答案 1 :(得分:0)
您发布的代码缺少大括号。在其他之前你需要一个额外的紧密支撑。大概你的真实代码不是,或者它不会编译。
在else子句中,为局部变量赋值不会做任何事情。
如果indexPath.section != 0
,您还需要执行某些操作。如果您什么都不做,您可能会获得之前构建的单元格的内容。如果您希望不显示视图,则必须将其删除。类似的东西:
for (UIView *subview in cell.contentView.subviews)
[subview removeFromSuperview];
但我认为如果你只为第1部分和其他部分使用不同的单元格标识符会更容易。然后,您将不会返回已用于第3节中第1节的单元格,并且必须重新配置它们。像:
NSString *CellIdentifier;
if (indexPath.section == 0)
CellIdentifier = @"Section1Cell";
else
CellIdentifier = @"OtherSectionCell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];