Search code examples
iosswiftuitableviewuiswitch

Unable to position UIElement(Switch) in Expandable table View Cell


Referring Above Image : I want to place UISwitch in Subcell of cell4.

I did this code to do this inside cellForRowAt indexPath

if(indexPath.section == 3) {

    if(indexPath.row == 0) {

        let mySwitch = UISwitch()
        let xpos = cell.frame.width - 60
        let ypos = cell.frame.origin.y + 6
        mySwitch.frame = CGRect(x: xpos, y: ypos, width:50, height: 26)
        mySwitch.setOn(true, animated: false)
        mySwitch.onTintColor = UIColor.init(red: 0.91, green: 0.30, blue: 0.24, alpha: 1.0)
        mySwitch.addTarget(self, action: #selector(switchChanged(sender:)), for: UIControlEvents.valueChanged)
        menuTableView.addSubview(mySwitch)
    }
}

Now What happening is : Initially Switch appearing on cell 1 when table view loads. After expanding and collapsing cell4 once , it appears at submenu of cell4. How to resolve this incorrect position issue?


Solution

  • You should append your switch to your cell instead of the tableView.