テーブルビューセルのUIButtonアクション 質問する

テーブルビューセルのUIButtonアクション 質問する

テーブル ビュー セル内でボタンが押されたときにアクションを実行しようとしています。次のコードは、テーブル ビュー コントローラ クラスにあります。

ボタンは、UITableViewCell のクラス「requestsCell」のアウトレットで「はい」と記述されています。

Parse を使用してデータを保存しており、ボタンが押されたときにオブジェクトを更新したいと考えています。objectIds 配列は正常に動作し、cell.yes.tag も正しい番号をログに出力しますが、クエリを適切に実行するためにその番号を「接続」関数に取り込むことができません。

適切な objectId を見つけるには、セルの indexPath.row を取得する方法が必要です。

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as requestsCell

    // Configure the cell...

    cell.name.text = requested[indexPath.row]

    imageFiles[indexPath.row].getDataInBackgroundWithBlock{
        (imageData: NSData!, error: NSError!) -> Void in

        if error == nil {

            let image = UIImage(data: imageData)

            cell.userImage.image = image
        }else{
            println("not working")
        }    
    }

    cell.yes.tag = indexPath.row
    cell.yes.targetForAction("connected", withSender: self)

    println(cell.yes.tag)

    return cell
}


func connected(sender: UIButton!) {

    var query = PFQuery(className:"Contacts")
    query.getObjectInBackgroundWithId(objectIDs[sender.tag]) {
        (gameScore: PFObject!, error: NSError!) -> Void in
        if error != nil {
            NSLog("%@", error)
        } else {
            gameScore["connected"] = "yes"
            gameScore.save()
        }
    }

}

ベストアンサー1

Swift 4 および Swift 5:

そのボタンのターゲットを追加する必要があります。

myButton.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)

もちろん、ボタンを使用するので、そのボタンのタグを設定する必要があります。

myButton.tag = indexPath.row

UITableViewCell をサブクラス化することでこれを実現できます。これをインターフェイス ビルダーで使用し、そのセルにボタンをドロップし、アウトレット経由で接続すれば完了です。

接続された関数でタグを取得するには:

@objc func connected(sender: UIButton){
    let buttonTag = sender.tag
}

おすすめ記事