当以编程方式使用日期选择器进行更改时,按钮标题始终会重置

时间:2014-12-11 18:54:45

标签: ios iphone swift uidatepicker

我有一个带标签的按钮"输入时间"当你点击按钮它会重新键盘并显示日期选择器时,当我更改日期值时,按钮上的文字会变为按预期约会。但是,如果我第二次更改日期,按钮标题将恢复为"输入时间",如果我再次更改日期,它会正确更改为日期,但是当我第四次更改日期时返回"输入时间",因此按钮文本每隔一段时间重置一次。我不确定为什么会这样。请参阅下面的代码:

    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
}

1 个答案:

答案 0 :(得分:2)

不要直接设置标签文字。告诉按钮标签文本应该是什么:

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