如何在类似Android的警报控制器中编写Swift数字选择器

问题描述 投票:1回答:1

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

在我的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)

    }
swift xcode uialertcontroller numberpicker
1个回答
0
投票
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])"
    }
}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.