Swift 之 UIPickView

首先我们签订两个代理

UIPickerViewDelegate,UIPickerViewDataSource




import UIKit

class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource{
   
    let pickerView = UIPickerView()

    
    override func viewDidLoad() {
        super.viewDidLoad()

          //坐标

        pickerView.frame = CGRect.init(x: 0.0, y: self.view.frame.size.height - 200.0, width: self.view.frame.size.width, height: 200.0)

       // 签订代理

       pickerView.delegate = self
        pickerView.dataSource = self

        //创建列数:第一个参数是出现时所在的行数,比如第一个改为 pickerView.selectRow(1, inComponent: 0, animated: true),视图出现时将会展现的是第一列的第二行(0为第一行)

        pickerView.selectRow(0, inComponent: 0, animated: true)
        pickerView.selectRow(0, inComponent: 1, animated: true)
        pickerView.selectRow(0, inComponent: 2, animated: true)
        self.view.addSubview(pickerView)
        //创建button按钮进行选择操作
        let button = UIButton.init(type: UIButtonType.custom)
        self.view.addSubview(button)
        button.frame = CGRect.init(x: 80, y: 100, width: 100, height: 50)
        button.setTitle("去人", for: .normal)
        button.backgroundColor = UIColor.orange
        button.addTarget(self, action: #selector(chick), for: .touchUpInside)
        
        
        
    }
    这里根据选择框的数据进行操作
    func chick() {
        
        let string = String(pickerView.selectedRow(inComponent: 0)) + "-" + String(pickerView.selectedRow(inComponent: 1)) + "-" + String(pickerView.selectedRow(inComponent: 2))
        print(string)
    }
    列数
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3
    }

    每列行数可以根据component修改每列的行数

    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, rowHeightForComponent component: Int) -> CGFloat {
        return 50
    }

    不仅仅可以展示字符串也可以展示自定义的UIView

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let image = UIImage(named:"1")
        let imageView = UIImageView()
        imageView.image = image
        return imageView
        
        
    }


   选择的行和列

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        print(component)
        print(row)
    }
    
}



这是基本的使用方法,最主要的应用就是制作地址选择器,代码太多在写就会很乱,直接粘贴地址,大家去下载看看好了

地址:https://github.com/NoPolun/SwifCity.git

你可能感兴趣的:(swift)