iOS-swift自定义控件下拉框

1.控件如图:

iOS-swift自定义控件下拉框_第1张图片
8DE5812A-BDA1-45FF-A02B-C2EEE1C72E62.png

iOS-swift自定义控件下拉框_第2张图片
CEA0CB94-56D7-4760-8949-B7EA98F13AC0.png

2.控件组成:

一个label和一个button 组成控件的主界面,2个view ,一个是弹出视图,一个是蒙板。

3. 思路

我通过一个lable 和一个带图片的button 创建 主界面,在创建一个containview用于显示要选择的内容文本,通过一个蒙板 来实现点击 控件外的区域实现 收起下拉视图。
#4.代码如下
import UIKit

//屏幕的宽和高 用于构建蒙板
let DeviceWidth = UIScreen.main.bounds.size.width
let DeviceHeight = UIScreen.main.bounds.size.height

class FLLSelectBox: UIView {

    var selectBoxLabel: UILabel!
    var coverView: UIView!
    var containView: UIView!
    var titles: [String] = []
    var containViewHeight = CGFloat(0)
    var isPullDown = false

    init(frame: CGRect,titles: [String]) {
        self.titles = titles
        super.init(frame: frame)
        self.layer.borderWidth = 2
        self.layer.borderColor = UIColor.blue.cgColor
        initView()
    }

    required init?(coder aDecoder: NSCoder) {
    
        fatalError("init(coder:) has not been implemented")
    }

    //初始化视图
    func initView() {
    
        let width = self.frame.size.width
        let height = self.frame.size.height
        selectBoxLabel = UILabel(frame: CGRect(x: 0.1 * width, y: 0, width: 0.5 * width , height: height ))
        selectBoxLabel.text = titles[0]
        let selectBoxBtn = UIButton(frame: CGRect(x: 0.7 * width, y: 0, width: 0.3 * width, height: height))
        selectBoxBtn.backgroundColor = UIColor.blue
        selectBoxBtn.setImage(UIImage(named: "selectBox1"), for: .normal)
        selectBoxBtn.addTarget(self, action: #selector(self.showContainView), for: .touchUpInside)
        self.addSubview(selectBoxLabel)
        self.addSubview(selectBoxBtn)
    
        containViewHeight = height * CGFloat(titles.count)
        containView =  UIView(frame: CGRect(x: self.frame.origin.x, y: self.frame.origin.y + height, width: self.frame.size.width, height: containViewHeight))
        containView.layer.borderWidth = 2
        containView.layer.borderColor = UIColor.blue.cgColor
        containView.backgroundColor = UIColor.lightGray
    
        for i in 0..

你可能感兴趣的:(iOS-swift自定义控件下拉框)