从Enum中获取数据以显示在UIPickerView上 [英] Take data from Enum to show on UIPickerView
问题描述
我正在创建一个简单的View,其中有一个UIPickerView,我想从枚举中显示PickerView上的选择。我创建了一个可能的饮料的枚举
I am creating a simple View where there is a UIPickerView and I want to display the choices on the PickerView from an enum. I have created an enum of possible drinks
enum drink{
case coffee
case tea
case cola
case water
}
我想知道可以在UIPickerView中显示饮料?我正在使用Swift 1.2和Xcode 6.3.1 ..谢谢! :)
I was wondering how it would be possible to display the drinks in an UIPickerView? I am using Swift 1.2 and Xcode 6.3.1.. Thanks!! :)
推荐答案
如 ABakerSmith
所述,您可以使用可打印协议在 UIPickerView
中显示 String
。
As mentioned by ABakerSmith
you can use the Printable protocol to display the String
in the UIPickerView
.
在最后,您可以拥有一个 ViewController
,如下所示:
In the end you can have a ViewController
looking as the following:
//
// ViewController.swift
// Test
//
// Created by Stefan Veis Pennerup on 04/05/15.
// Copyright (c) 2015 Kumuluzz. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var pickerView: UIPickerView!
enum Drink: Int, Printable {
case Coffee = 0
case Tea = 1
case Cola = 2
case Water = 3
static var count: Int { return Drink.Water.rawValue + 1 }
var description: String {
switch self {
case .Coffee: return "Coffee"
case .Tea : return "Tea"
case .Cola : return "Cola"
case .Water : return "Water"
default: return ""
}
}
}
// MARK: - UIPickerViewDataSource
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return Drink.count
}
// MARK: - UIPickerViewDelegate
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return Drink(rawValue: row)?.description;
}
// several optional methods:
// func pickerView(pickerView: UIPickerView!, widthForComponent component: Int) -> CGFloat
// func pickerView(pickerView: UIPickerView!, rowHeightForComponent component: Int) -> CGFloat
// func pickerView(pickerView: UIPickerView!, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString!
// func pickerView(pickerView: UIPickerView!, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView!
// func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int)
}
这篇关于从Enum中获取数据以显示在UIPickerView上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!