xcode Swift 4 中的日期/时间选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49991549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 10:37:32  来源:igfitidea点击:

Date/Time Picker in Swift 4

swiftxcodedatetimepickeruidatepickerpicker

提问by Thomas

How would I make a Time/Date Picker that allows a selection of minutes and seconds and set that as a countdown time (I only need to know how to make the Time/Date Picker). I've found many tutorials but they are made in the Main.storyboard. I want to add it to my GameScene.swift (file type is Cocoa Touch Class). I am working with Swift 4 in Xcode 9.3 in a Game type application.

我将如何制作允许选择分钟和秒并将其设置为倒计时时间的时间/日期选择器(我只需要知道如何制作时间/日期选择器)。我找到了很多教程,但它们是在 Main.storyboard 中制作的。我想将它添加到我的 GameScene.swift(文件类型是 Cocoa Touch Class)。我正在 Xcode 9.3 中的游戏类型应用程序中使用 Swift 4。

Thanks in advance!

提前致谢!

回答by Khushbu

You want minutes and seconds picker. So, default UIDatePicker does not provide this functionality. So, I have make custom picker using UIPickerView.

你想要分秒选择器。因此,默认的 UIDatePicker 不提供此功能。所以,我使用 UIPickerView 制作了自定义选择器。

1) First, write this code in viewDidLoad() method.

1) 首先,在 viewDidLoad() 方法中编写这段代码。

    let timePicker: UIPickerView = UIPickerView()
    //assign delegate and datasoursce to its view controller
    timePicker.delegate = self
    timePicker.dataSource = self

    // setting properties of the pickerView
    timePicker.frame = CGRect(x: 0, y: 50, width: self.view.frame.width, height: 200)
    timePicker.backgroundColor = .white

    // add pickerView to the view
    self.view.addSubview(timePicker)

2) Second, make extension of your viewcontroller and give them UIPickerViewDelegate and UIPickerViewDataSource as I have done below.

2)其次,扩展你的视图控制器并给他们 UIPickerViewDelegate 和 UIPickerViewDataSource ,就像我在下面所做的那样。

extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource{

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 2
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 60
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return String(format: "%02d", row)
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0{
            let minute = row
            print("minute: \(minute)")
        }else{
            let second = row
            print("second: \(second)")
        }
    }
}

Hope this will help you.

希望这会帮助你。