2011-12-12 14 views
0

我與他們多張圖像的表格視圖單元格。當觸摸他們所拍攝的圖像時,會在圖像頂部顯示一個覆蓋圖,告訴用戶該圖像已被選中。如何改變一個的UITableViewCell當它觸及

有沒有辦法改變只有一個UITableViewCell的外觀,而不必做一個[tableView reloadData],這將允許我在表視圖數據源委託方法中以不同方式設置單元格的樣式。

回答

1

我會做的方式,它是繼承UITableViewCell,然後tableView:didSelectRowAtIndexPath:獲取到單元格的引用,做任何你想要它(或只是針對圖像的觸摸事件,如果這不是一個選擇)。

也許有另一種方法做到這一點,而不必子類,但我發現自己一直劃分UITableViewCell,這是非常簡單的做。

1

如果你希望避免的子類,這可以利用手勢識別器來實現的。您的問題表明每個圖片上的Tap and Hold用戶互動,我已在下面的代碼中實施。有一點要記住,如果用戶點擊並按住,他們可能看不到您希望這些文字看。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
static NSString *cellIdentifier = @"ImageCell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

if (!cell) { 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease]; 
} 

UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)]; 

UILongPressGestureRecognizer *recognizer2 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)]; 

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Ben.png"]]; 
imageView.frame = CGRectMake(cell.contentView.bounds.origin.x,cell.contentView.bounds.origin.y , 100, 40); 
imageView.userInteractionEnabled = YES; 
[imageView addGestureRecognizer:recognizer]; 
[cell.contentView addSubview:imageView]; 

UIImageView *imageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Steve.png"]]; 
imageView2.frame = CGRectMake(cell.contentView.bounds.origin.x + imageView.frame.size.width + 10,cell.contentView.bounds.origin.y , 100, 40); 
imageView2.userInteractionEnabled = YES; 
[imageView2 addGestureRecognizer:recognizer2]; 
[cell.contentView addSubview:imageView2]; 

[imageView release]; 
[imageView2 release]; 
[recognizer release]; 
[recognizer2 release]; 

return cell;} 



- (void)imageTapped:(id)sender { 
    NSLog(@"%@", sender); 

    UILongPressGestureRecognizer *recognizer = (UILongPressGestureRecognizer *)sender; 

    if (recognizer.state == UIGestureRecognizerStateBegan) { 
     UILabel *label = [[UILabel alloc] initWithFrame:recognizer.view.bounds]; 
     label.text = @"Pressed"; 
     label.backgroundColor = [UIColor clearColor]; 
     label.tag = 99999; 
     label.textColor = [UIColor whiteColor]; 
     [recognizer.view addSubview:label]; 
     [label release]; 
    } 
    else { 
     [[recognizer.view viewWithTag:99999] removeFromSuperview]; 
    } 
} 

希望這會有所幫助。

相關問題