import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
let pv = UIPickerView()
let items = [
["アイカツ", "プリパラ", "アイマス"],
["いちご", "ゆりか", "みずき", "あかり", "らぁら", "みれぃ", "そふぃ", "あんず"]
]
var anime = ""
var chara = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
// Alert
let title = "トップアイドル"
let message = "好きなアイドルを選択してください.\n\n\n\n\n\n\n\n" //改行入れないとOKCancelがかぶる
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:{
(action: UIAlertAction!) -> Void in
print("あなたの好きなアイドルは、\(self.anime)の\(self.chara)です.")
})
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action in
}
// PickerView
pv.selectRow(0, inComponent: 0, animated: true) // 初期値
pv.frame = CGRectMake(0, 50, view.bounds.width * 0.85, 150) // 配置、サイズ
pv.dataSource = self
pv.delegate = self
alert.view.addSubview(pv)
alert.addAction(okAction)
alert.addAction(cancelAction)
presentViewController(alert, animated: true, completion: nil)
}
// PickerViewの列数
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return items.count
}
// PickerViewの行数
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return items[component].count
}
// PickerViewの項目
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return items[component][row]
}
// PickerViewの項目選択時
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0 {
anime = items[0][row]
} else {
chara = items[1][row]
}
print("\(items[component][row])")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme