有没有办法在Swift上隐藏UIDatePicker?

时间:2015-10-19 20:42:33

标签: xcode swift

我试图隐藏我的日期选择器,直到我的textField被选中。我这样做只是为了我有一个pickerView。但是,我无法找到使用Swift显示的解决方案,然后在textField上隐藏datePicker。

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

@IBOutlet weak var TeeTimes: UILabel!
@IBOutlet weak var textFieldDate: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var picker: UIPickerView! = UIPickerView()
@IBOutlet weak var textfieldCourse: UITextField!


var pickerData = ["Norman Course", "Riding Golf", "Dmob Course"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    picker.hidden = true;
    self.textfieldCourse.delegate = self
    self.picker.delegate = self
    self.picker.dataSource = self
    textfieldCourse.text = pickerData[0]
    //Inputs the data into the array
    datePicker.hidden = true;
    datePicker.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: UIControlEvents.ValueChanged)

}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.

}
func numberOfComponentsInPickerView(pickerView: UIPickerView) ->Int {
    return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) ->Int {
    return pickerData.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return pickerData[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){
    textfieldCourse.text = pickerData[row]
    picker.hidden = true
}
func textFieldShouldBeginEditing(textfield: UITextField) ->Bool {
    picker.hidden = false
    return false
}
func datePickerChanged(dataPicker: UIDatePicker) {
    datePicker.hidden = false
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle

    let strDate = dateFormatter.stringFromDate(datePicker.date)
    textFieldDate.text = strDate
}

}

2 个答案:

答案 0 :(得分:1)

我不明白为什么你不能使用相同的原则,因为 UIDatePicker UIPickerView 都是 UIView的子类。只需将 textFieldDate 的委托设置为 self ,并在 textFieldShouldBeginEditing 中应用相同的逻辑。只有您必须检查正在编辑的文本字段才能显示正确的选择器。

此外,您应该在 datePickerChanged 函数中将 datePicker.hidden 设置为 true ,假设您希望在日期之后隐藏日期选择器被选中了。

答案 1 :(得分:0)

我们绝对可以使用自动布局和设置约束来隐藏空间并折叠不同的视图。您可以为不同的对象设置自动布局并设置日期选择器的高度。将高度约束拖放到控制器中,并提供名称drag and drop constraint。它看起来像这个link

接下来,将viewDidLoad()中的约束设置为0 va_list &ap

现在,您隐藏了datePicker,将高度设置为0,当您显示datePicker时,将高度设置为所需的高度。 你可以起诉datePickerHeight.constant = 0