Search code examples
iosswift3xib

Provide action for button in the xib file using swift3


PROVIDED: I have a button in my xibenter image description here The swift file associated with this is also attached.

ISSUE: this cell has a button that need to display a ViewController on the button click. This cell is attached to the table view in another ViewController. I want to implement an action on the button "BOOK" so as on clicking the new view controller should open. i am not able to do this can any one suggest me something that i should do?

CODE:

import UIKit

class HotelBookingCell: UITableViewCell {

    @IBOutlet weak var BookbtnOutlet: UIButton!
    override func awakeFromNib() {
        super.awakeFromNib()
        BookbtnOutlet.layer.cornerRadius = 7
        // Initialization code
    }

    @IBAction func bookbtn1(_ sender: Any) {

    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

Solution

  • remove the following code in tableviewcell class

    /*
    @IBAction func bookbtn1(_ sender: Any) {
    
    } */
    

    and add into your UIviewcontroller cellForRowAtIndexPath

    cell. BookbtnOutlet.tag = indexpath.row
    cell. BookbtnOutlet.addTarget(self, action: #selector(self. bookbtn1(_:)), for: .touchUpInside);
    

    And anywhere in the same UIVeiwController define the function as below

    func bookbtn1(_ sender : UIButton){
    // call your segue code here
    }