简体   繁体   中英

Button title always resets when programmatically using date picker to change it

I have a button with a label "Enter time", when u click the button it resigns the keyboard and shows a date picker, when I change the date value, the text on the button changes to that date as expected. But if I change the date for a second time the button title reverts back to "Enter time", if i change the date again, it changes correctly to the date but then when i change it the fourth time it goes back to "Enter time", so the button text resets every other time. I am not sure why this is happening. See my code below:

    override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    composeTextView.becomeFirstResponder()
    addFunListButton.backgroundColor = UIColor(red: 0xf5/255, green: 0xa6/255, blue: 0x23/255, alpha: 1.0)
    addFunListButton.tintColor = UIColor.whiteColor()

    nowTimeButton.backgroundColor = UIColor(red: 0xe9/255, green: 0x7f/255, blue: 0x02/255, alpha: 1.0)
    nowTimeButton.tintColor = UIColor.whiteColor()

    enterTimeButton.backgroundColor = UIColor(red: 0xe9/255, green: 0x7f/255, blue: 0x02/255, alpha: 0.8)
    enterTimeButton.tintColor = UIColor.whiteColor()

    datePickerBox.addTarget(self, action: Selector("eventTime"), forControlEvents: UIControlEvents.ValueChanged)

    // Setting up the date picker
    let currentDate = NSDate()
    datePickerBox.minimumDate = currentDate
    datePickerBox.date = currentDate

}

@IBAction func datePickerBoxAction(sender: UIDatePicker) {
    printDate(sender.date)
}

func printDate(date:NSDate){

    let dateFormatter = NSDateFormatter()

    var theDateFormat = NSDateFormatterStyle.ShortStyle
    let theTimeFormat = NSDateFormatterStyle.ShortStyle

    dateFormatter.dateStyle = theDateFormat
    dateFormatter.timeStyle = theTimeFormat

    NSLog("%@", date)
    enterTimeButton.titleLabel?.text = dateFormatter.stringFromDate(date)
    eventTime = date
}

Don't set the label text directly. Tell the button what the label text should be:

let title = dateFormatter.stringFromDate(date)
enterTimeButton.setTitle(title, forState:UIControlState.Normal)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM