Swift之時(shí)間選擇器

先看效果:

屏幕快照 2017-04-07 上午11.57.23.png

首先,把控件的尺寸和間距寫成宏,方便后續(xù)修改

import UIKit
fileprivate let kGaoJianLongScreenWidth: CGFloat = UIScreen.main.bounds.size.width
fileprivate let kGaoJianLongScreenHeight: CGFloat = UIScreen.main.bounds.size.height

fileprivate let kGaoJianLongWidthScale: CGFloat = 375.0
fileprivate let kGaoJianLongHeightScale: CGFloat = 667.0

//彈窗距離左右邊距
fileprivate let kGaoJianLongSpaceLeftOrRight: CGFloat = 35
//彈窗距離上邊距
fileprivate let kGaoJianLongSpaceTop: CGFloat = 114
//彈窗寬度
fileprivate let kGaoJianLongPopView_Width: CGFloat = kGaoJianLongScreenWidth - (kGaoJianLongSpaceLeftOrRight * 2)
//彈窗高度
fileprivate let kGaoJianLongPopView_Height: CGFloat = 220
//時(shí)間選擇器的高度
fileprivate let kGaoJianLongDatePicker_Height: CGFloat = 200

聲明屬性(類似視圖類的屬性用懶加載的方式較好些)

    // 代理屬性
    var delegate : JLBTimePopViewDelegate?
    
    // MARK: 屬性
    fileprivate lazy var coverView : UIView = {
        let v = UIView()
        v.frame = CGRect.init(x: 0, y: 0, width: kGaoJianLongScreenWidth, height: kGaoJianLongScreenHeight)
        v.backgroundColor = UIColor.black
        v.alpha = 0
        
        return v
    }()
    
    fileprivate lazy var popView : UIView = {
        let v = UIView()
        v.frame = CGRect.init(x: kGaoJianLongSpaceLeftOrRight, y: kGaoJianLongSpaceTop, width: kGaoJianLongPopView_Width, height: kGaoJianLongPopView_Height)
        v.backgroundColor = UIColor.white
        v.layer.masksToBounds = true;
        v.layer.cornerRadius = 10;
        v.alpha = 0
        
        return v
    }()
    
    fileprivate lazy var startBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.setTitleColor(JLBTimePopView.kRgbColor(r: 51, g: 51, b: 51), for: .normal)
        btn.setTitleColor(JLBTimePopView.kRgbColor(r: 15, g: 156, b: 254), for: .selected)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 17);
        btn.titleLabel?.textAlignment = .right;
        btn.addTarget(self, action: #selector(startBtnAction(btn:)), for: .touchUpInside)
        
        let date = self.datePicker.date
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let titleString = dateFormatter.string(from: date)
        btn.setTitle(titleString, for: .normal)
        
        btn.isSelected = true
        return btn
    }()
 
    fileprivate lazy var endBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.setTitleColor(JLBTimePopView.kRgbColor(r: 51, g: 51, b: 51), for: .normal)
        btn.setTitleColor(JLBTimePopView.kRgbColor(r: 15, g: 156, b: 254), for: .selected)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
        btn.titleLabel?.textAlignment = .left
        btn.addTarget(self, action: #selector(endBtnAction(btn:)), for: .touchUpInside)
        
        btn.setTitle("2016-09-30", for: .normal)
        return btn
    }()
    
    fileprivate lazy var cancelBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.frame = CGRect.init(x: 0, y: self.popView.frame.height - 49, width: (self.popView.frame.width - 1) / 2.0, height: 49)
        btn.setTitle("取消", for: .normal)
        btn.setTitleColor(JLBTimePopView.kRgbColor(r: 51, g: 51, b: 51), for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        btn.addTarget(self, action: #selector(cancelBtnAction), for: .touchUpInside)

        return btn
    }()
    
    fileprivate lazy var confirmBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        let x: CGFloat = self.popView.frame.width - self.cancelBtn.frame.width - 1
        let y: CGFloat = self.popView.frame.height - 49
        let w: CGFloat = (self.popView.frame.width - 1) / 2.0
        let h: CGFloat = 49
        btn.frame = CGRect.init(x: x, y: y, width: w, height: h)
        btn.setTitle("確定", for: .normal)
        btn.setTitleColor(JLBTimePopView.kRgbColor(r: 51, g: 51, b: 51), for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        btn.addTarget(self, action: #selector(confirmBtnAction), for: .touchUpInside)
        
        return btn
    }()
    
    fileprivate var datePicker: UIDatePicker = UIDatePicker()

初始化

class JLBTimePopView: UIView {
       
    override init(frame: CGRect)
    {
        super.init(frame: frame)
        
        UIApplication.shared.keyWindow?.addSubview(self)
        self.frame = self.superview?.bounds ?? UIScreen.main.bounds
        
        self.addSubview(coverView)
        self.addSubview(datePicker)
        self.addSubview(popView)
        
        setDatePickerStyle()
        setPopView()
    }

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

    class func shareTimePopView() -> JLBTimePopView
    {
        return JLBTimePopView.init(frame: UIScreen.main.bounds)
    }
     
    class func showPopView(delegate:JLBTimePopViewDelegate) -> JLBTimePopView
    {
        let popView = JLBTimePopView.shareTimePopView()
        popView.delegate = delegate
        popView.show()
        
        return popView
    }
 
    class func showPopView(delegate: JLBTimePopViewDelegate, startDate: String, endDate: String) -> JLBTimePopView
    {
        let popView = JLBTimePopView.shareTimePopView()
        popView.delegate = delegate
        
        let formatter = DateFormatter()
        formatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd")
        let date = formatter.date(from: startDate)
        
        popView.datePicker.setDate(date ?? popView.datePicker.date, animated: false)
        popView.startBtn.setTitle(startDate, for: .normal)
        popView.endBtn.setTitle(endDate, for: .normal)
        
        popView.show()
        return popView
    }
    
    fileprivate func show()
    {
        UIView.animate(withDuration: 0.25, animations: { [weak self] in
            self?.coverView.alpha = 0.5;
            self?.popView.alpha = 1;
            self?.datePicker.alpha = 1;
        }) { (finished) in
            
        }
    }
    
    fileprivate func dismiss()
    {
        UIView.animate(withDuration: 0.25, animations: { [weak self] in
            self?.coverView.alpha = 0;
            self?.popView.alpha = 0;
            self?.datePicker.alpha = 0;
        }) { (finished) in
            self.removeFromSuperview()
        }
    }
}

swift中類方法的聲明,在func標(biāo)識(shí)符之前加一個(gè)class即可

//類方法
    class func shareTimePopView() -> JLBTimePopView
    {
        return JLBTimePopView.init(frame: UIScreen.main.bounds)
    }

對象方法的聲明,直接用func標(biāo)識(shí)即可

//實(shí)例方法
    func startBtnAction(btn: UIButton)
    {
        btn.isSelected = true
        endBtn.isSelected = false
        
        rollCurrentDate(btn: btn)
    }

蘋果官方建議,把數(shù)據(jù)源代理方法單獨(dú)寫到一個(gè)擴(kuò)展中,以便提高代碼的可讀性
在這里,我把自定義的一些私有方法寫在了擴(kuò)展中,同樣是為了提高代碼可讀性
格式如下:

extension + 類名 { 
}

extension JLBTimePopView {

}

extension JLBTimePopView {
    
    fileprivate class func kRgbColor(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor
    {
        return UIColor.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1)
    }
    
    fileprivate func rollCurrentDate(btn: UIButton)
    {
        let dateStr: String? = btn.currentTitle
        let formatter: DateFormatter = DateFormatter()
        formatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd")
        
        let date: Date = formatter.date(from: dateStr ?? "2017-06-06")!
        datePicker.setDate(date, animated: true)
    }
    
    /// 設(shè)置日期選擇器相關(guān)屬性
    fileprivate func setDatePickerStyle()
    {
        datePicker.alpha = 0
        datePicker.frame = CGRect.init(x: 0, y: kGaoJianLongScreenHeight - kGaoJianLongDatePicker_Height + 20, width: kGaoJianLongScreenWidth, height: kGaoJianLongDatePicker_Height)
        datePicker.backgroundColor = UIColor.white
        datePicker.datePickerMode = .date;
        
        let minDate: Date = Date.init(timeIntervalSince1970: 60 * 60)
        let maxDate: Date = Date.init(timeIntervalSinceNow: 60 * 60)
        
        datePicker.minimumDate = minDate
        datePicker.maximumDate = maxDate
        
        datePicker.addTarget(self, action: #selector(datePicekerValueChanged(picker:)), for: .valueChanged)
    }
    
    /// 設(shè)置popView上的子控件
    fileprivate func setPopView()
    {
        //第一部分
        let titleLabel = UILabel()
        titleLabel.frame = CGRect.init(x: 0, y: 0, width: popView.frame.width, height: 50)
        titleLabel.text = "請選擇統(tǒng)計(jì)時(shí)間"
        titleLabel.font = UIFont.systemFont(ofSize: 14)
        titleLabel.textColor = JLBTimePopView.kRgbColor(r: 153, g: 153, b: 153)
        titleLabel.textAlignment = .center;
        popView.addSubview(titleLabel)

        let topLineView = UIView()
        topLineView.frame = CGRect.init(x: 0, y: 50, width: popView.frame.width, height: 1)
        topLineView.backgroundColor = JLBTimePopView.kRgbColor(r: 242, g: 242, b: 242)
        popView.addSubview(topLineView)
        
        //第二部分
        popView.addSubview(self.startBtn)
        self.startBtn.frame = CGRect.init(x: 20, y: topLineView.frame.maxY + 20, width: (popView.frame.width - 60) / 2.0, height: popView.frame.height - 100 - 40)

        let tempLabel = UILabel()
        tempLabel.frame = CGRect.init(x: self.startBtn.frame.maxX, y: self.startBtn.frame.minY, width: 20, height: self.startBtn.frame.height)
        tempLabel.textAlignment = .center
        tempLabel.text = "至"
        tempLabel.font = UIFont.systemFont(ofSize: 14)
        tempLabel.textColor = JLBTimePopView.kRgbColor(r: 153, g: 153, b: 153)
        popView.addSubview(tempLabel)
        
        popView.addSubview(self.endBtn)
        self.endBtn.frame = CGRect.init(x: tempLabel.frame.maxX, y: self.startBtn.frame.minY, width: self.startBtn.frame.width, height: self.startBtn.frame.height)
        
        let bottomLineView = UIView()
        bottomLineView.frame = CGRect.init(x: 0, y: kGaoJianLongPopView_Height - 50, width: popView.frame.width, height: 1)
        bottomLineView.backgroundColor = JLBTimePopView.kRgbColor(r: 242, g: 242, b: 242)
        popView.addSubview(bottomLineView)
        
        //第三部分
        popView.addSubview(self.cancelBtn)
        
        let verticalLineView: UIView = UIView()
        verticalLineView.frame = CGRect.init(x: self.cancelBtn.frame.width, y: self.cancelBtn.frame.minY, width: 1, height: self.cancelBtn.frame.height)
        verticalLineView.backgroundColor = JLBTimePopView.kRgbColor(r: 242, g: 242, b: 242)
        popView.addSubview(verticalLineView)
        
        popView.addSubview(self.confirmBtn)
    }
}

使用的時(shí)候把JLBTimePopView.swift這個(gè)類拷貝到項(xiàng)目中,調(diào)用方式如下:

    func showNewOrder(btn: UIButton)
    {
        print("\("新訂單")")
        
        _ = JLBTimePopView.showPopView(delegate: self as JLBTimePopViewDelegate)        
    }

實(shí)現(xiàn)代理方法,獲取選中的日期時(shí)間:

extension ViewController: JLBTimePopViewDelegate 
{    
    func getStartDate(startDate: String, endDate: String)
    {
        print("開始時(shí)間:\(startDate)" + "結(jié)束時(shí)間:\(endDate)")
    }
}

項(xiàng)目地址:https://github.com/Fei627/SwiftDemo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,182評(píng)論 6 543
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,489評(píng)論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,290評(píng)論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,776評(píng)論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,510評(píng)論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,866評(píng)論 1 328
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,860評(píng)論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,036評(píng)論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,585評(píng)論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,331評(píng)論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,536評(píng)論 1 374
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,058評(píng)論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,754評(píng)論 3 349
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,154評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,469評(píng)論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,273評(píng)論 3 399
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,505評(píng)論 2 379

推薦閱讀更多精彩內(nèi)容