2017-09-23 81 views
0

我有一個表格視圖,它的單元格本身有一個按鈕,這些按鈕應該用唯一的ID打開一個視圖。所以我需要傳遞一個參數給我的按鈕,但是addTarget屬性我可以調用沒有任何參數的函數。在表視圖單元格中添加按鈕的目標

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
... 
    cell.editButton.addTarget(self, action: #selector(goToEdit(id:)), for: .touchUpInside) 
} 

func goToEdit(id: String) { 
    let edit = EditAdViewController(editingAdId: id) 
    self.navigationController?.pushViewController(edit, animated: true) 
} 

有什麼辦法可以將一些參數的動作引用到按鈕上嗎?謝謝大家:)

+0

https://stackoverflow.com/a/46379494/3746301 – Shades

回答

0

也許你可以嘗試將你的按鈕鏈接到@IBAction並使用params [indexPath.row]。

要獲得indexPath:

var cell = sender.superview() as? UITableViewCell 
var indexPath: IndexPath? = yourTableView.indexPath(for: cell!) 
+0

不幸#selector不能得到任何參數 –

+0

嘗試你按鈕鏈接到@IBAction和使用PARAMS [indexPath.row]。 得到indexPath: var cell = sender.superview()as? UITableViewCell var indexPath:IndexPath? = yourTableView.indexPath(for:cell!) – 2017-09-23 21:30:59

+0

@LucasMoraes不要在註釋中張貼代碼。 [編輯]你的答案將全部相關細節。 – rmaddy

0

你可以嘗試將委託功能,以您的自定義的UITableViewCell。

例如,我有這樣的習俗tableViewCell內的按鈕:

PickupTableViewCell.swift

import UIKit 

protocol PickupTableViewCellDelegate: NSObjectProtocol { 
    func pickupTableViewCell(userDidTapPickup pickup: Pickup, pickupTableViewCell: PickupTableViewCell) 
} 

class PickupTableViewCell: UITableViewCell { 

    // MARK: - Properties 

    @IBOutlet private weak var label_UserFullName: UILabel! 
    .... 

    // MARK: - Functions 
    // MARK: IBAction 

    @IBAction func pickup(_ sender: Any) { 
     self.delegate?.pickupTableViewCell(userDidTapPickup: self.pickup, pickupTableViewCell: self) 
    } 
} 

然後在我通過UITableViewDataSource (cellForRow),當然符合我的控制器實現的委託功能我tableViewCell。

HomeViewController.swift

// MARK: - UITableViewDataSource 

extension HomeViewController: UITableViewDataSource { 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let pickupTVC = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.pickupTableViewCell)! 
     pickupTVC.delegate = self 
     pickupTVC.pickup = self.pickups[indexPath.section] 

     return pickupTVC 
    } 
} 

// MARK: - PickupTableViewCellDelegate 

extension HomeViewController: PickupTableViewCellDelegate { 
    func pickupTableViewCell(userDidTapPickup pickup: Pickup, pickupTableViewCell: PickupTableViewCell) { 
     // Do something 
    } 
} 
相關問題