2014-11-12 12 views
12

Chcę wykonać przejście z przycisku w niestandardowej UITableViewCell, ale nie wiem, jak uzyskać dostęp do zawartości komórki po naciśnięciu tego przycisku. Zdaję sobie sprawę, że można to osiągnąć poprzez didSelectRowAtIndexPath, jednak mam tę metodę wykonującą inną funkcję i chciałbym użyć przycisku, który utworzyłem w komórce tabeli.Wykonywanie przejścia z przycisku wewnątrz niestandardowego UITableViewCell

Tu jest moja metoda wykonywania segue Mam problem z:

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 
    } 
} 

otagować przycisk w komórce podczas wyświetlania go i dać mu działanie docelowa:

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) 
} 

Tutaj to czynność, która jest wywoływana po naciśnięciu przycisku:

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

Każda pomoc jest doceniana. Dzięki!

+0

Może chcesz przekazać nie siebie, ale przycisk lub komórkę jako nadawcę? –

+0

użyj delegata, aby osiągnąć coś takiego.Delegat zostanie zdefiniowany w klasie CustomCell, a na TableViewController ustawi delegata każdej komórki ... Na UITableViewController określ metodę delegata, która będzie Cię nazywała. performSegueWithIdentifier ... Z czystej ciekawości, co robisz z "didSelectRowAtIndexPath"? –

Odpowiedz

30

Utwórz protokół z metodą, która zostanie wywołana przez CustomCell za delegata zdefiniowany na 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) 
} 

Teraz za pomocą protokołu na 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) 

} 

} 

Zdefiniuj Delegata na swoje Niestandardowa komórka i wywołanie wewnątrz nowego przycisku Funkcja delegata.

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) 
      } 
    } 
} 

Mam nadzieję, że to może być czyste i zrozumiałe, aby zrozumieć i wdrożyć w swoim kodzie.

+0

Jak utworzyć przejście przy użyciu storyboardu? gdzie mam CTRL + przeciągnąć? –

+0

@ ChristopherFrancisco CTRL + Przeciągnij z kontrolera, z którego chcesz przejść do kontrolera docelowego, i pokaż mu kilka opcji, takich jak: Pokaż, naciśnij, modalnie coś takiego. I to wszystko. Aha i pamiętaj, aby dodać identyfikator do nowo utworzonego segue. –

+0

Jak utworzyć protokół? Oczywiście naśladuje przedstawiony kod, ale w którym ViewController? Czy protokoły są niezależne? Jeśli samodzielne, czy tworzę całkiem nowy plik Swift? –

0

Znalazłem szybszą odpowiedź na przekazanie danych za pomocą przycisku w dynamicznej komórce do nowego VC.

  1. Konfigurowanie Tableview, komórkę niestandardowy (podłącz komórkę z utworzonej klasy i ustawić na komórkach identyfikator) i utworzyć nowy VC i podłączyć go za pomocą segue (również ustawić identyfikator dla segue) do bieżącej TableViewController

  2. konfigurowania komórkę z gniazdka (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) 
        } 
    } 
    
  3. funkcji CellForRowAt w TableViewController klasy

    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) 
    } 
    
  4. ustanowić metodę przycisk, który jest nazywany przez cel przycisku

    func buttonTapped(_ sender:UIButton!){ 
        self.performSegue(withIdentifier: "customSegueIdentifier", sender: sender) 
    } 
    
  5. przygotować dla funkcji 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 
          } 
         } 
        } 
    } 
    

nadzieję, że ten kod pomogą wam. zachowaj kodowanie;)

+0

Dziękujemy! Doceniam twój wkład i twój wysiłek w kompilowanie tego rozwiązania! Czy mógłbyś wyjaśnić nieco, jak jest szybsza? – user3353890

Powiązane problemy