Expanding and collapsing UITableViewCells with DatePicker

后端 未结 6 1436
一生所求
一生所求 2020-12-02 05:21

I\'m building an app that lets the user select dates from a UITableView. The tableView is static and grouped. I\'ve looked through many questions, including this one, trying

6条回答
  •  盖世英雄少女心
    2020-12-02 06:02

    The 2 answers above enabled me to solve this problem. They deserve the credit, I'm adding this a reminder for myself - summary format.

    This is my version of the above answers.

    1. As noted above - add picker to a the cell you want to show / hide.

    2. Add constraints for the picker in interface builder - center X / center Y / equal height / equal width to the cell's content view

    3. Connect the picker to you VC

    @IBOutlet weak var dobDatePicker: UIDatePicker!
    

    You might as well control drag and add a method that will register the date changes

    @IBAction func dateChanged(sender: UIDatePicker) { 
        // updates ur label in the cell above
        dobLabel.text = "\(dobDatePicker.date)"
    }
    

    4. In viewDidLoad

    dobDatePicker.date = NSDate()
    dobLabel.text = "\(dobDatePicker.date)" // my label in cell above
    dobDatePicker.hidden = true
    

    5. Setting cell heights, in my example the cell I want to expand is section 0, row 3... set this to what you cell you want to expand / hide. If you have many cells with various heights this allows for that.

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    
        if indexPath.section == 0 && indexPath.row == 3 {
            let height:CGFloat = dobDatePicker.hidden ? 0.0 : 216.0
            return height
        }
    
        return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
    }
    

    6. Selecting the cell above to expand the one below, again set this to the cell you will tap to show the cell below.

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    
    let dobIndexPath = NSIndexPath(forRow: 2, inSection: 0)
    if dobIndexPath == indexPath {
    
        dobDatePicker.hidden = !dobDatePicker.hidden
    
        UIView.animateWithDuration(0.3, animations: { () -> Void in
            self.tableView.beginUpdates()
            // apple bug fix - some TV lines hide after animation
            self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
            self.tableView.endUpdates()
        })
    }
    }
    

提交回复
热议问题