您的位置:首页 > 移动开发 > Swift

UIPickerView swift

2016-12-16 23:46 309 查看
//

// ViewController.swift

// UILabelTest

//

// Created by mac on 15/6/23.

// Copyright (c) 2015年 fangyuhao. All rights reserved.

//

import UIKit

class ViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate {

var pickerView:UIPickerView!

override func viewDidLoad() {
super.viewDidLoad()
pickerView = UIPickerView()
pickerView.dataSource = self
pickerView.delegate = self
//设置选择框的默认值
pickerView.selectRow(1, inComponent: 0, animated: true)
pickerView.selectRow(2, inComponent: 1, animated: true)
pickerView.selectRow(3, inComponent: 2, animated: true)
self.view.addSubview(pickerView)
//建立一个按钮,触摸按钮时获得选择框被选择的索引
var button = UIButton(frame: CGRectMake(0, 0, 100, 30))
button.center = self.view.center
button.backgroundColor = UIColor.blueColor()
button.setTitle("获取信息", forState: .Normal)
button.addTarget(self, action: "getPickerViewValue", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)

// Do any additional setup after loading the view, typically from a nib.
}
//设置选择框的列数为3列
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 3
}
//设置选择框行数为9行
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 9
}
//设置选择框各选项的内容,
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return String(row)+"-"+String(component)
}
//调整选择框的尺寸
func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
if(0==component){
return 100
}else{
return 30
}
}
//检测行的选择状态
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
println(component)
println(row)
}
//触摸时,获得选中的索引
func getPickerViewValue(){
var alertView = UIAlertView()
alertView.title = "被选中的索引为"
alertView.message = String(pickerView.selectedRowInComponent(0))+"-"+String(pickerView.selectedRowInComponent(1))+"-"+String(pickerView.selectedRowInComponent(2))
alertView.addButtonWithTitle("OK")
alertView.show()
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: