Swift-XCode - 如何让文本字段具有用户可以选择的设置值?
Swift-XCode - How to let Text Field have set values the user can choose from?
我了解普通文本字段的工作原理,用户可以在其中输入自己的文本,但是有没有一种方法可以让用户单击 text field
并出现一些选项,例如 "Hello"、"Bye" 和 "Goodnight"?
它有点像一个带有更多选项的占位符,而占位符在这方面实际上没有作用,因为当用户单击文本字段时,会弹出文本选项 select,并且用户可以 select 文本,该文本将用于文本字段。
谢谢!
您想使用UIPickerView and the inputView
property of UITextField
实施以下方法:
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)
}
}
我了解普通文本字段的工作原理,用户可以在其中输入自己的文本,但是有没有一种方法可以让用户单击 text field
并出现一些选项,例如 "Hello"、"Bye" 和 "Goodnight"?
它有点像一个带有更多选项的占位符,而占位符在这方面实际上没有作用,因为当用户单击文本字段时,会弹出文本选项 select,并且用户可以 select 文本,该文本将用于文本字段。
谢谢!
您想使用UIPickerView and the inputView
property of UITextField
实施以下方法:
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)
}
}