Swift-XCode - 如何让文本字段设置用户可以选择的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27735888/
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 06:26:40  来源:igfitidea点击:

Swift-XCode - How to let Text Field have set values the user can choose from?

iosiphonexcodeswift

提问by Justin Rose

I understand how the normal text field works where the user can input their own text, but is there a way where the user clicks the text fieldand it comes up with some options, such as "Hello", "Bye", and "Goodnight"?

我了解普通文本字段是如何工作的,用户可以在其中输入自己的文本,但是有没有办法让用户单击text field它并提供一些选项,例如“你好”、“再见”和“晚安”?

It's sort of like a placeholder with more options, and the placeholder really isn't in effect in this because when the user clicks the text field, the options pop up for text to select, and the user can select the text and that text will be used in the text field.

它有点像一个有更多选项的占位符,占位符在这方面真的不起作用,因为当用户点击文本字段时,选项会弹出供选择的文本,用户可以选择文本,该文本将用于文本字段。

Thanks!

谢谢!

回答by Midhun MP

You want to use UIPickerViewand the inputViewproperty of UITextField

你想使用UIPickerViewUITextFieldinputView属性

Implement the methods like:

实现如下方法:

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate
{

    @IBOutlet weak var textField: UITextField!
    var dataObject : [String] = ["Hello","Bye","Good Night"];

    override func viewDidLoad()
    {
        super.viewDidLoad()
        let picker = UIPickerView()
        picker.delegate   = self
        picker.dataSource = self

        self.textField.inputView = picker
    }

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
    {
        return 1;
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
    {
        return self.dataObject.count;
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!
    {
        return self.dataObject[row];
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        self.textField.text = self.dataObject[row];
        self.textField.endEditing(true)
    }
}