如何在像 Android 这样的警报控制器中编写 Swift 数字选择器

Vic*_*rcé 1 xcode numberpicker swift uialertcontroller

如何创建一个由变量定义的最小值和最大值的数字选择器?

在我的 Android 应用程序中,我创建了一个带有选择器编号的 AlertDialog,并且最大编号链接到我的数据库中的一个值。

是否有可能在 Swift 或接近它的地方做同样的事情?

我的警报控制器代码是:

func createAlertCarte1(Title:String, Message:String) {
        let alertCarte1 = UIAlertController(title: Title, message: Message, preferredStyle: UIAlertController.Style.alert)
        alertCarte1.addAction(UIAlertAction.init(title: "Ok", style: UIAlertAction.Style.default, handler: { (action1) in
            alertCarte1.dismiss(animated: true, completion: nil)
            self.displayAd()
        }))
        alertCarte1.addAction(UIAlertAction.init(title: "Annuler", style: UIAlertAction.Style.cancel, handler: { (action1) in
            alertCarte1.dismiss(animated: true, completion: nil)
        }))

        self.present(alertCarte1, animated: true, completion: nil)

    }
Run Code Online (Sandbox Code Playgroud)

rba*_*win 7

import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    var pickerView: UIPickerView!
    var pickerData: [Int]!

    override func viewDidLoad() {
        super.viewDidLoad()
        pickerView = UIPickerView(frame: CGRect(x: 10, y: 50, width: 250, height: 150))
        pickerView.delegate = self
        pickerView.dataSource = self

        // This is where you can set your min/max values
        let minNum = 1
        let maxNum = 10
        pickerData = Array(stride(from: minNum, to: maxNum + 1, by: 1))
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        showAlert()
    }

    func showAlert() {
        let ac = UIAlertController(title: "Picker", message: "\n\n\n\n\n\n\n\n\n\n", preferredStyle: .alert)
        ac.view.addSubview(pickerView)
        ac.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
            let pickerValue = self.pickerData[self.pickerView.selectedRow(inComponent: 0)]
            print("Picker value: \(pickerValue) was selected")
        }))
        ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        present(ac, animated: true)
    }

    func numberOfComponents(in 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])"
    }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • `\n` 是新行 - 这是一种通过添加空行为选择器创建一些空间的技巧。可能有更好的方法。 (2认同)