1

내있는 tableView의 모든 세포는 accessoryView로 UISwitch가 : 사용자가 도청 때활성화 세포의 액세서리보기 (UISwitch가)

UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectZero]; 
cell.accessoryView = mySwitch; 
[mySwitch addTarget:self action:@selector(SwitchToggle:) forControlEvents:UIControlEventValueChanged]; 

스위치가 전환됩니다, 그러나 나는 또한 때를 전환하려면 didSelectRowAtIndexPath가 호출됩니다 (사용자가 해당 셀을 누를 때).

나는이 시도 (그러나 그것은 작동하지 않습니다) :

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UISwitch *tempSwitch = (UISwitch *)[tableView cellForRowAtIndexPath:indexPath].accessoryView; 
    [tempSwitch addTarget:self action:@selector(SwitchToggle:) forControlEvents:UIControlEventValueChanged]; 

    [tableView deselectRowAtIndexPath:indexPath animated:YES]; // cell selection fadeout animation 
} 

감사합니다.

+0

"작동하지 않는 경우"는 어떻게됩니까? 마치 didSelectRowAtIndexPath :가없는 것처럼 전혀 아무런 조치도 취하지 않았다. – dasblinkenlight

답변

1

코드는 다음과 같이해야합니다

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UISwitch *tempSwitch = (UISwitch *)[tableView cellForRowAtIndexPath:indexPath].accessoryView; 
    [tempSwitch setOn:!tempSwitch.on animated:YES]; 
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; 
} 

당신은 또한 당신의 모델을 업데이트해야 할 것을 기억하십시오.

+0

스위치를 토글하지만 내 모델을 업데이트하는 (switchToggle :) 액션을 호출하지 않습니다. 이 문제를 해결할 수있는 해결 방법을 제시하겠습니다. 감사! – budidino

+1

"해결 방법"은 다음 행을 추가하는 것입니다 :'[self switchToggle : tempSwitch];'. –

관련 문제