Search code examples
swift4.1

How to navigate through button programmatically


I have created a table view cell in story board and i created a cocoa touch class for it.In that it will have one button, so here i want to navigate to another view controller on clicking on the button programmatically.

This my code

@IBOutlet weak var findOutButton: UIButton!

override func awakeFromNib()
{
    super.awakeFromNib()

   findOutButton.addTarget(self, action: Selector(("action:")), for: UIControlEvents.touchUpInside)

}
func action(sender: UIButton) {


let vc5 = self.storyboard.instantiateViewController(withIdentifier: "DescriptionViewController") as? DescriptionViewController

    self.navigationController?.pushViewController(vc5!, animated: true)
}

Here its showing error in this line

let vc5 = self.storyboard.instantiateViewController(withIdentifier: "DescriptionViewController") as? DescriptionViewController ` like "value of type 'TableViewCell' has no member 'storyboard'.

Thanks in advance.Help me to clear out the error.


Solution

  • You cannot access self.storyboard from your UITableCell. You should navigate from the main ViewController, that contains your UITableView. And for this you need to use delegates. At top of your UITableCell class add this :-

    protocol CustomTableDelegate {
        func DelegateButtonPressed()
    }
    class YourClass : UITableViewCell{
    var delegate : CustomTableDelegate? = nil
    
    override func awakeFromNib()
    {
        super.awakeFromNib()
    
       findOutButton.addTarget(self, action: Selector(("action:")), for: UIControlEvents.touchUpInside)
    
    }
    func action(sender: UIButton) {
    
    self.delegate?.DelegateButtonPressed()
    }
    }
    

    And In your main View Controller in which you have your UITableView, in

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "YourClass", for: indexPath) as! YourClass
    cell.delegate = self
    return cell
    }
    

    And also add delegate as :-

    class YOURVIEWCONTROLLER:UIViewController, CustomTableDelegate{
    func DelegateButtonPressed(){
    let vc5 = self.storyboard.instantiateViewController(withIdentifier: "DescriptionViewController") as? DescriptionViewController
    
        self.navigationController?.pushViewController(vc5!, animated: true)
    }
    }
    

    Let me know if you find any difficulty using this.