6

カスタムボタンをに追加していUITableViewCellます。そのボタンのアクションで、showAlert:関数を呼び出し、メソッドにセルラベルを渡します。

showAlertこのメソッドでパラメータを渡すにはどうすればよいaction:@selector(showAlert:)ですか?

4

3 に答える 3

9

TableviewcellでButtonを使用している場合は、各セルのボタンにタグ値を追加し、パラメーターとしてidを使用してメソッドaddTargetを設定する必要があります。

サンプルコード:

メソッドに以下のコードを入力する必要があります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
}
于 2009-10-02T10:44:40.547 に答える
2

それは可能ではありません。IBActionに準拠したメソッドを作成する必要があります

- (IBAction)buttonXYClicked:(id)sender;

このメソッドでは、UIAlertViewを作成して呼び出すことができます。ボタンをInterfaceBuilderのメソッドに接続することを忘れないでください。

複数のボタンを区別したい場合(たとえば、各テーブルセルに1つある場合)、ボタンのタグプロパティを設定できます。次に、クリックが発生するボタンのsender.tagを確認します。

于 2009-10-02T09:53:21.827 に答える
1

Jayの答えは素晴らしいですが、複数のセクションがある場合、indexRowはセクションに対してローカルであるため、機能しません。

複数のセクションがあるTableViewでボタンを使用している場合の別の方法は、タッチイベントを渡すことです。

レイジーローダーでボタンを宣言する場所:

- (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いつでもindexPathを提供する便利な関数です。locationInViewまた、特定のindexPathを正確に特定できるように、tableViewのコンテキストでタッチする必要があるため、関数も重要です。

これにより、複数のセクションがあるテーブルで、それがどのボタンであったかを知ることができます。

于 2013-05-01T17:52:03.873 に答える