2012-08-30 46 views
8

我有一個UITableview,我正在顯示一些任務,並且每行都有一個用於標記任務是否完成的複選框。選擇UITableViewCell AccessoryView,與選擇行分開

我正在尋找當用戶點擊複選框時切換複選標記,並在用戶點擊該行時切換到詳細視圖。後者很容易,只要通過使用

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 

不過,我想選擇區域分開,選擇accessoryview當只有切換的複選框,並進入只有當所選單元格的其餘部分詳細視圖。如果我在accessoryview內添加UIbutton,那麼當用戶只想點擊複選框時,用戶將選擇行AND UIButton,對不對?

另外,如果用戶只是沿着accessoryview拖動瀏覽tableview呢?這不會觸發TouchUp上的UIButton的操作嗎?

任何人有任何想法如何做到這一點?謝謝你的時間!

回答

16

如何管理這個委託的方法內配件龍頭:

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath 

編輯:

你可以做這樣的事情對於響應accessoryButtonTappedForRowWithIndexPath:方法定製accessoryView的。

cellForRowAtIndexPath:方法 -

BOOL checked = [[item objectForKey:@"checked"] boolValue]; 
UIImage *image = (checked) ? [UIImage imageNamed:@"checked.png"] : [UIImage imageNamed:@"unchecked.png"]; 

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height); 
button.frame = frame; 
[button setBackgroundImage:image forState:UIControlStateNormal]; 

[button addTarget:self action:@selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside]; 
button.backgroundColor = [UIColor clearColor]; 
cell.accessoryView = button; 

- (void)checkButtonTapped:(id)sender event:(id)event 
{ 
    NSSet *touches = [event allTouches]; 
    UITouch *touch = [touches anyObject]; 
    CGPoint currentTouchPosition = [touch locationInView:self.tableView]; 
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition]; 
    if (indexPath != nil) 
    { 
    [self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath]; 
    } 
} 

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath 
{ 
    NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row]; 
    BOOL checked = [[item objectForKey:@"checked"] boolValue]; 
    [item setObject:[NSNumber numberWithBool:!checked] forKey:@"checked"]; 

    UITableViewCell *cell = [item objectForKey:@"cell"]; 
    UIButton *button = (UIButton *)cell.accessoryView; 

    UIImage *newImage = (checked) ? [UIImage imageNamed:@"unchecked.png"] : [UIImage imageNamed:@"checked.png"]; 
    [button setBackgroundImage:newImage forState:UIControlStateNormal]; 
} 
+1

你如何讓你的自定義附件按鈕調用回表視圖的委託? –

+0

哇,我不知道我是如何錯過的,對於愚蠢的問題感到抱歉,並感謝您的幫助!我會給你一個鏡頭,這聽起來就是我想要的。 – Cody

+1

@CarlVeazey好處,文檔說accessoryButtonTappedForRowWithIndexPath響應披露按鈕附件類型,這不是我想使用的類型,因爲我想要一個複選框。 我可以通過使用詳細視圖的披露按鈕來解決這個問題,並點擊該行的其餘部分以在該行的其他地方切換複選標記,但那不是我想要的。 – Cody