Sri Sumi
Sri Sumi

Reputation: 55

How to get the indexpath of UISwitch in dynamic tableview using swift?

I'm creating an online Test app. In that for selecting the subject, I have a dynamic tableview with UISwitch. In that table I have 10 subjects in 10 rows. I need to find the indexPath of each switch to get the subject name.

I'm new to ios. I need the answer in swift.

Upvotes: 0

Views: 1150

Answers (3)

NANNAV
NANNAV

Reputation: 4901

Use this Simple code to find indexpath from Subview

func indexPathForCellContainingView(switch: UISwitch, inTableView tableView:UITableView) -> NSIndexPath? {
    let viewCenterRelativeToTableview = tableView.convertPoint(CGPointMake(CGRectGetMidX(view.bounds), CGRectGetMidY(view.bounds)), fromView:view)
    return tableView.indexPathForRowAtPoint(viewCenterRelativeToTableview)
}

Upvotes: 0

Tejas Ardeshna
Tejas Ardeshna

Reputation: 4371

this code will be in your cellForRowAtIndexPath

  var subSwitch:UISwitch! //your switch or you can get this by viewWithTag also
            subSwitch.restorationIdentifier = "\(indexPath.row)"
            subSwitch.addTarget(self, action: "swichValueChange:", forControlEvents: UIControlEvents.ValueChanged)

now get evnt for value change

 func swichValueChange (sender : UISwitch)
    {
       var id:String = sender.restorationIdentifier
    //here you can identify,which Switch is changed
    }

Upvotes: 3

Chetan Prajapati
Chetan Prajapati

Reputation: 2297

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

         //here you can get uiswitch object
}

Upvotes: 0

Related Questions