Подтвердить что ты не робот

Выполнение segue с кнопки в пользовательском UITableViewCell

Я хочу выполнить segue с помощью кнопки в пользовательском UITableViewCell, но я не знаю, как получить доступ к содержимому ячейки, когда я нажимаю эту кнопку. Я понимаю, что это может быть достигнуто с помощью didSelectRowAtIndexPath, однако у меня есть этот метод, выполняющий другую функцию, и я хотел бы использовать кнопку, которую я создал в ячейке таблицы.

Вот мой метод segue, с которым у меня возникают проблемы:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
    if segue.identifier == "showComments"
    {
        let vc:CommentOnPostViewController = segue.destinationViewController as CommentOnPostViewController

        var buttonPosition:CGPoint = sender?.convertPoint(CGPointZero, toView: self.feed) as CGPoint!
        var path:NSIndexPath = self.feed.indexPathForRowAtPoint(buttonPosition) as NSIndexPath!

        var postToCommentOn:PFObject = feedList[path.row] as PFObject
        vc.post = postToCommentOn as PFObject
    }
}

Я отмечаю кнопку в ячейке при ее отображении и даю ей целевое действие:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    // There is code that goes here for creating and displaying the cell.

    cell.commentButton.tag = indexPath.row
    cell.commentButton.addTarget(self, action: "addComment", forControlEvents: UIControlEvents.TouchUpInside)
}

Вот действие, которое вызывается при нажатии кнопки:

func addComment()
{
    self.performSegueWithIdentifier("showComments", sender: self)
}

Любая помощь приветствуется. Спасибо!

4b9b3361

Ответ 1

Создайте протокол с помощью метода, который будет вызываться делегатом CustomCell, определенным на вашем TableViewController

//Pass any objects, params you need to use on the 
//segue call to send to the next controller.

protocol MyCustomCellDelegator {
    func callSegueFromCell(myData dataobject: AnyObject)
}

Теперь используйте протокол в вашем UITableViewController

class MyTableViewController : UITableViewController, MyCustomCellDelegator {


 //The usual Defined methods by UIViewController and UITableViewController 

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

  //Set the CustomCell new Delegate
  var cell = tableView.dequeueReusableCellWithIdentifier(customIdentifier) as MyCustomCell


  cell.delagete = self

  return cell

 }


 //MARK: - MyCustomCellDelegator Methods

 func callSegueFromCell(myData dataobject: AnyObject) {
   //try not to send self, just to avoid retain cycles(depends on how you handle the code on the next controller)
   self.performSegueWithIdentifier("showComments", sender:dataobject )

 }

}

Определите делегата в своей пользовательской ячейке и вызове внутри вашей новой кнопки функцию делегата.

class MyCustomCell : UITableViewCell {

      var delegate:MyCustomCellDelegator!
      @IBOutlet weak var myButton:UIButton



     @IBAction func buttonPressed(sender:AnyObject){
           var mydata = "Anydata you want to send to the next controller"
           if(self.delegate != nil){ //Just to be safe.
             self.delegate.callSegueFromCell(mydata)
           }
    }
}

Надеюсь, это может быть чистым и понятным для вас, чтобы вы могли понять и реализовать в своем коде.

Ответ 2

Я нашел более быстрый ответ для передачи данных с помощью кнопки в динамической ячейке на новый VC.

  • Настройка Tableview, настраиваемой ячейки (соедините ячейку с вашим созданным классом и установите идентификатор ячейки) и создайте новый VC и подключите его через segue (также установите идентификатор для segue), чтобы ваш текущий TableViewController

  • настройка вашей ячейки с выходом (cellButton)

    class CustomCell: UITableViewCell {
        @IBOutlet weak var cellButton: UIButton!
    
    
       override func awakeFromNib() {
           super.awakeFromNib()
       }
    
       override func setSelected(_ selected: Bool, animated: Bool) {
          super.setSelected(selected, animated: animated)
       }
    }
    
  • Функция CellForRowAt в классе TableViewController

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomCell
    
        //...Do stuff for your cell
    
        cell.cellButton.tag = indexPath.row //or value whatever you want (must be Int)
        cell.cellButton.addTarget(self, action: #selector(TableViewController.buttonTapped(_:)), for: UIControlEvents.touchUpInside)
     }
    
  • настройте метод кнопки, который вызывается мишенью кнопки

    func buttonTapped(_ sender:UIButton!){
        self.performSegue(withIdentifier: "customSegueIdentifier", sender: sender)
    }
    
  • подготовьтесь к функции segue

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if(segue.identifier == "customSegueIdentifier") {
            if let destination = segue.destination as? YourNewViewController {
    
               if let button:UIButton = sender as! UIButton? {
                   print(button.tag) //optional
                   destination.valueViaSegue = button.tag
               }
            }
        }
    }
    

Надеюсь, этот код поможет вам, ребята. сохранить кодирование;)

Ответ 3

Вот что я сделал

В вашем классе UITableViewCell добавлено следующее

protocol MyCustomCellDelegator {

    func callSegueFromCell(myData dataobject: AnyObject)

}
class MyUITableViewCell: UITableViewCell {

    var delegate:MyCustomCellDelegator!

    .......


    @IBAction func buttonPress (_ sender: Any){


        if(self.delegate != nil){

            self.delegate.callSegueFromCell(myData: )

        }

    }

}

И в UITableViewController

class STVHomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MyCustomCellDelegator {


    .....

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        if let cell = tableView.dequeueReusableCell(withIdentifier: "MyIdentifier") as? MyIdentifierCell {

            // configure your cell
            cell.configureCell(myIdentifier:)

            // This line is important 
            cell.delegate = self

            return cell

        } else {

            return MyIdentifierCell()
        }

    }

    func callSegueFromCell(myData dataobject: AnyObject) {

        print(dataobject)
        self.performSegue(withIdentifier: "goToNextVC", sender: dataobject )


    }

}