PickerView、DatePicker

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //UIView: UITableView
        let pickerView = UIPickerView(frame: CGRect(x: 0, y: 100, width: self.view.bounds.size.width, height: 200))
        pickerView.dataSource = self
        pickerView.delegate = self
        self.view.addSubview(pickerView)
        
        //UIControl
        let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 300, width: self.view.bounds.size.width, height: 200))
//        datePicker.datePickerMode = .Date
        datePicker.datePickerMode = .Time
        datePicker.addTarget(self, action: #selector(didChange(_:)), forControlEvents: .ValueChanged)
        self.view.addSubview(datePicker)
    }
    
    func didChange(sender: UIDatePicker) {
        print(sender.date) //NSDate
    }

    //列数
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 3
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 4
    }
    
//    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
//        return "a"
//    }
    
    //可以重用
    func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
        if let v = view {
            print("reusing")
            v.backgroundColor = UIColor.redColor()
            return v
        }
        else {
            print("no reuse")
            let greenView = UIView()
            greenView.backgroundColor = UIColor.greenColor()
            return greenView
        }
    }
    
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        print("\(component): \(row)")
    }
}

你可能感兴趣的:(PickerView、DatePicker)