//遵守协议时需要把必须遵守的协议都实现了否则报红
UIPickerViewDelegate,UIPickerViewDataSource
创建PickerView
pickerView = UIPickerView()
pickerView.delegate = self
pickerView.dataSource = 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)
UIPickerViewDataSource
//选择框的列数为
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 3
}
//选择框的行数
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 5
}
UIPickerViewDelegate
//设置选择框各选项显示的内容
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return String(row)+"-"+String(component)
}
//单个选择框的高度
func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 50.0
}
//单个选择框的宽度
func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return self.view.frame.size.width/3
}
//将图片作为选择框选项
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView {
let image = UIImage(named: "\(row%2)")
let imageView = UIImageView(image: image)
return imageView
}
//响应事件滑到什么位置了
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print(row,component)
}
建立一个按钮,触摸按钮时获得选择框被选择的索引
let button = UIButton(type: .Custom)
button.frame = CGRectMake(50, 200, 280, 50)
button.backgroundColor = UIColor.orangeColor()
button.setTitle("确定", forState: .Normal)
button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
button.addTarget(self, action: Selector("getPickerinfo"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
//获取选择框上面的信息
func getPickerinfo(){
let OkMessage = "\(pickerView.selectedRowInComponent(0)) and \(pickerView.selectedRowInComponent(1)) and \(pickerView.selectedRowInComponent(2))"
print(OkMessage)
}
来源: http://www.cnblogs.com/spaceID/p/4977131.html