조치 : @selector (showalert :)이 showalert 메소드에서 매개 변수를 전달하는 방법은 무엇입니까?
-
19-09-2019 - |
문제
내 커스텀 버튼을 추가하고 있습니다 UITableViewCell
. 그 버튼의 동작에서 전화하고 싶습니다 showAlert:
이 방법에서 셀 레이블을 전달하고 싶다.
이것에서 매개 변수를 어떻게 전달할 수 있습니까? showAlert
방법: action:@selector(showAlert:)
?
해결책
그건 불가능하다. iBaction을 준수하는 메소드를 만들어야합니다
- (IBAction)buttonXYClicked:(id)sender;
이 방법에서는 UialertView를 작성하고 호출 할 수 있습니다. 인터페이스 빌더의 메소드와 버튼을 연결하는 것을 잊지 마십시오.
여러 버튼 (예 : 각 테이블 셀에 하나가 있음)을 구별하려면 버튼의 태그 속성을 설정할 수 있습니다. 그런 다음 Click이 나오는 버튼에서 sender.tag를 확인하십시오.
다른 팁
TableViewCell에서 버튼을 사용하는 경우 각 셀의 버튼에 태그 값을 추가하고 addTarget 메소드를 ID를 매개 변수로 설정해야합니다.
샘플 코드 :
아래 코드를 입력해야합니다 cellForRowAtIndexPath
방법.
{
// Set tag to each button
cell.btn1.tag = indexPath.row;
[cell.btn1 setTitle:@"Select" forState:UIControlStateNormal]; // Set title
// Add Target with passing id like this
[cell.btn1 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
-(void)btnClick:(id)sender
{
UIButton* btn = (UIButton *) sender;
// here btn is the selected button...
NSLog(@"Button %d is selected",btn.tag);
// Show appropriate alert by tag values
}
Jay의 대답은 훌륭하지만 여러 섹션이 있으면 Indexrow가 이후로 작동하지 않습니다. 섹션에 로컬.
또 다른 방법은 여러 섹션이있는 테이블 뷰에서 버튼을 사용하는 경우 터치 이벤트를 통과하는 것입니다.
게으른 로더로 버튼을 선언하는 곳 :
- (UIButton *)awesomeButton
{
if(_awesomeButton == nil)
{
_awesomeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[_awesomeButton addTarget:self.drugViewController action:@selector(buttonPressed:event:) forControlEvents:UIControlEventTouchUpInside];
}
return _awesomeButton;
}
여기서 핵심은 이벤트를 선택기 메소드에 묶는 것입니다. 자신의 매개 변수를 전달할 수는 없지만 이벤트를 전달할 수 있습니다.
버튼 기능이 다음과 같이 연결됩니다.
- (void)buttonPressed:(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];
NSLog(@"Button %d was pressed in section %d",indexPath.row, indexPath.section);
}
여기의 핵심은 기능입니다 indexPathForRowAtPoint
. 이것은 멋진 기능입니다 UITableView
그것은 당신에게 언제든지 인덱스 경로를 줄 것입니다. 또한 기능도 중요합니다 locationInView
테이블 뷰의 컨텍스트에서 터치가 필요하므로 특정 인덱스 경로를 정확히 찾아 낼 수 있습니다.
이렇게하면 여러 섹션이있는 테이블에 어떤 버튼이 있는지 알 수 있습니다.