SpaceX
SpaceX

Reputation: 2890

TableViewCell updating incorrectly - iOS, Swift

I have a custom cell with a DatePicker, when the user clicks the cell, the cell expands to its full view showing the date picker (I have attached an image of the custom cell). I am trying to update the start time based on the date picker selection.

When I change the time in datepicker: - for the first time it updates the date correctly - Second time goes back to it's original value

Could someone please suggest, how I could fix this issue ?

class DailyTimesTableViewCell: UITableViewCell {


    @IBOutlet weak var startTime: UIButton!
    @IBOutlet weak var datePicker: UIDatePicker!

    @IBAction func timePickerChanged(_ sender: UIDatePicker) {

        startTime.titleLabel?.text = convertDateToString(sender.date)

    }
   func convertDateToString(_ dateObject: Date) -> String{
        let dateFormatter           = DateFormatter()
        dateFormatter.timeStyle = .short
        let dateString = dateFormatter.string(from: dateObject)
        return dateString
    }
}

Below is the gif showing the Error

error

Below is the custom cell

customCell

Upvotes: 0

Views: 66

Answers (1)

Jason Nam
Jason Nam

Reputation: 2011

You have to set the title of the button with the following method.

func setTitle(String?, for: UIControlState)

I replicated the problem and resolve by replacing the line

startTime.titleLabel?.text = convertDateToString(sender.date)

with

startTime.setTitle(convertDateToString(sender.date), for: .normal)

This is a very common mistakes I make many times.

Upvotes: 1

Related Questions