Swift -封装弹出筛选选择视图

工具文件:SelectItemView

import UIKit
protocol selectItemDelegate:NSObjectProtocol {//设置代理
    func selectData(str:NSString)
}
class SelectItemView: UIView,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource{
    weak var delegate:selectItemDelegate?
    var backgroundBtn = UIButton()
    var tfBackgroundView = UIView()
    var tf = UITextField()
    
    var tableView = UITableView()
    var cancelBtn = UIButton()
    var confirmBtn = UIButton()
    
    var selectRow = -1
    
    var dataSource = [[String:String]]()
    var allArr = [[String:String]]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
     
        //初始化属性配置

        self.initDataSource()
        
        //-----背景按钮
        backgroundBtn = UIButton(frame:CGRect(x:0,y:0,width:ScreenWidth,height:ScreenHeight))
        backgroundBtn.addTarget(self, action: #selector(onCilckCancel), for: UIControlEvents.touchUpInside)
        backgroundBtn.backgroundColor = UIColor.init(red: 145/255.0, green: 145/255.0, blue: 145/255.0, alpha: 0.8)
        self.addSubview(backgroundBtn)
        
        let viewX:CGFloat = 10
        let viewW:CGFloat = ScreenWidth-20
        
        let tfBackgroundViewY:CGFloat = 134
        let tfBackgroundViewH:CGFloat = 50
        
        //------输入框背景
        tfBackgroundView = UIView(frame:CGRect(x:viewX,y:tfBackgroundViewY,width:viewW,height:tfBackgroundViewH))
        tfBackgroundView.backgroundColor = UIColor.white
        self.addSubview(tfBackgroundView)

        tf=UITextField(frame:CGRect(x:5,y:5,width:tfBackgroundView.frame.size.width-10,height:tfBackgroundView.frame.size.height-10))
        tf.placeholder = "请输入"
        
        let leftView = UIView(frame:CGRect(x:0,y:0,width:40,height:40))
        let leftImgView = UIImageView(frame:CGRect(x:10,y:10,width:20,height:20))
        leftImgView.image = UIImage.init(named:"search")
  
        leftView.addSubview(leftImgView)
        
        tf.leftView = leftView
        tf.delegate = self
        tf.leftViewMode = UITextFieldViewMode.always
        tf.keyboardType = UIKeyboardType.default
        tf.returnKeyType = UIReturnKeyType.done//设置中文输入的时候换行键改为完成键
        tf.addTarget(self, action:#selector(textFieldChange(tf:)), for:.editingChanged)
        
        //输入框和列表的分割线
        myUnitilty.creatLineLable(x: 0, y: tfBackgroundView.frame.size.height-1, width: tfBackgroundView.frame.size.width, height: 1, backgroundColor: lineGrayColor, superView: tfBackgroundView)
        tfBackgroundView.addSubview(tf)
        
        //创建输入框背景左上角、右上角的圆角
        myUnitilty.creatViewTopCornerRadius(view: tfBackgroundView, cornerRadius: 8)
      
        let tabY:CGFloat = tfBackgroundView.frame.origin.y+tfBackgroundView.frame.size.height
        
        var tabH:CGFloat = ScreenHeight-204-100.0
       
        if ScreenHeight-204-100 > CGFloat(dataSource.count) * cellRowHeight {
            tabH = CGFloat(dataSource.count) * cellRowHeight
        }
        
       tableView= UITableView(frame:CGRect(x:tfBackgroundView.frame.origin.x,y:tabY,width:tfBackgroundView.frame.size.width,height:tabH))
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView()
        self.addSubview(tableView)
        
        let cancelAndConfirmBackgroundView = myUnitilty.creatViewReturnView(x: viewX, y: tableView.frame.size.height+tableView.frame.origin.y, width: viewW, height: 50, backgroundColor: UIColor.white, superView: backgroundBtn)
        //受背景按钮的影响要设置按钮背景的用户交互,
        cancelAndConfirmBackgroundView.isUserInteractionEnabled = true
        
        myUnitilty.creatLineLable(x: 0, y: 0, width: cancelAndConfirmBackgroundView.frame.size.width, height: 1, backgroundColor: lineGrayColor, superView: cancelAndConfirmBackgroundView)

        //创建取消确定按钮背景左下角、右下角的圆角
        myUnitilty.creatViewBottomCornerRadius(view: cancelAndConfirmBackgroundView, cornerRadius: 8)
        
        let cancelBtn = myUnitilty.creatButton(x: 0, y: 1, width: cancelAndConfirmBackgroundView.frame.size.width/2, height: 49, title: "取消", titleColor: UIColor.gray, superView: cancelAndConfirmBackgroundView)
        cancelBtn.addTarget(self, action: #selector(onCilckCancel), for: UIControlEvents.touchUpInside)
       
        myUnitilty.creatLineLable(x: cancelBtn.frame.size.width-1, y: 0, width: 1, height: cancelBtn.frame.size.height, backgroundColor: lineGrayColor, superView: cancelBtn)
        
      let confirmBtn = myUnitilty.creatButton(x: cancelAndConfirmBackgroundView.frame.size.width/2, y: 1, width: cancelAndConfirmBackgroundView.frame.size.width/2, height: 49, title: "确定", titleColor: UIColor.blue, superView: cancelAndConfirmBackgroundView)
        
        confirmBtn.addTarget(self, action: #selector(onCilckConfirm), for: UIControlEvents.touchUpInside)
    }

    func initDataSource() {
        
        for i in 1...10 {
            let dic = NSMutableDictionary()
            dic["itemName"] = "测试\(i)"
            allArr.append(dic as! [String : String])

        }
        dataSource = allArr
    }
    //MARK: tableViewDelegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return cellRowHeight
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier:String = "cell"
        
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier as String)
        if cell == nil {
            cell = UITableViewCell(style:.default, reuseIdentifier:nil)
        }
        let dic = dataSource[indexPath.row]
        if selectRow == indexPath.row {
            cell?.accessoryType = UITableViewCellAccessoryType.checkmark
        }
        cell?.textLabel?.text = dic["itemName"]! as String
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        selectRow = indexPath.row
        let dic = dataSource[indexPath.row]
        tf.text = dic["itemName"]! as String
        
        tableView.reloadData()
    }
    
    func onCilckCancel(){
        self.removeFromSuperview()
    }
    func onCilckConfirm(){

        if selectRow == -1 {
            myUnitilty.creatPopLable(text: "请选择产品!")
            return
        }

        let dic:NSDictionary = dataSource[selectRow] as NSDictionary
        self.delegate?.selectData(str: dic["itemName"]  as! NSString)
        self.removeFromSuperview()
    }
    
    //MARK:textFieldDelegate
    func textFieldChange(tf:UITextField){
        selectRow = -1//初始化选中的标记

        if tf.text == "" {
            dataSource = allArr
        }else{
            if tf.markedTextRange == nil{//没有输入拼音的时候筛选
                dataSource.removeAll()
                for var dic:[String:String] in allArr {
                    let str:NSString = dic["itemName"]! as NSString
                    
                    if str.contains(tf.text!) {
                        dataSource.append(dic)
                    }
                }
            }
        }
        tableView.reloadData()
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        print("textFieldDidEndEditing:\(textField.text! as String)")
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return false
    }


在viewController调用

   func onClickAction() {
        var isExist = false
        //判断选择SelectItemView是否已存在,不存在则创建
        for view:UIView in self.view.subviews {
            if view.isKind(of: SelectItemView.self){
                isExist = true
            }
        }
        if isExist == false {
            let selectView = SelectItemView(frame:CGRect(x:0,y:0,width:ScreenWidth,height:ScreenHeight))
            selectView.delegate = self
            self.view?.addSubview(selectView)
        }
    }

   //点击确定按钮的回调
    func selectData(str: NSString) {
        print(str)
    }


   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值