action:@selector(showAlert:) この showAlert メソッドでパラメータを渡す方法は?

StackOverflow https://stackoverflow.com/questions/1508453

質問

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

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

役に立ちましたか?

解決

それは不可能です。あなたはIBActionに準拠した方法を作成する必要があります。

- (IBAction)buttonXYClicked:(id)sender;

この方法では、UIAlertViewを作成して呼び出すことができます。 Interface Builderでの方法でボタンを接続することを忘れないでください。

は、(例えば、各表のセル内のいずれかを有する)複数のボタンを区別したい場合は、ボタンのタグのプロパティを設定することができます。 [OK]をクリックしますが来るのボタンからsender.tagを確認します。

他のヒント

あなたはTableviewcellのボタンを使用している場合、Uは、各セルのボタンにタグ値を追加し、パラメータとして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
}

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

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

遅延ローダーでボタンを宣言する場所:

- (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のコンテキストでタッチする必要があるためです。

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top