Swift之代理实现

需求是实现一个倒计时抢单功能,为了准确起见,倒计时到最后时需要验证服务器,重新获取服务器时间调整倒计时,我自己分装了一个显示倒计时的Label,当然为了实现时间的校准和倒计时结束后,UI界面的调整,涉及到了代理去实现这些功能。

先看效果图:

声明代理方法

// 声明设置代理方法
protocol PreviewCountdownLabelDelegate : class {
      func PreviewCountdownLabelExhaust()
      func PreviewCountdownLabelCorrectTime()
}

class PreviewCountdownLabel: UILabel {

    static let preTimeFormatter = NSDateFormatter(dateFormat: "HH:mm:ss")
    var isFirst = 0

    weak var delegate : PreviewCountdownLabelDelegate?
    let timet = NSDate().timeIntervalSinceDate(NSDate().dateByAddingTimeInterval(16 * 60 * 60))
    
    var expectedTime = NSDate() {
        didSet {
       }
}

var timeExpectedTime = NSDate() {
    didSet {
    }
}

var showChinese = false

var timer : NSTimer!

init() {
    super.init(frame: CGRectZero)
    FUCKINIT()
}

override init(frame: CGRect) {
    super.init(frame: frame)
    FUCKINIT()
}

func FUCKINIT() {
    textColor(UIColor.whiteColor())
    textAlignment(.Right)
    font(systemFontOfSize: 20)
    timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "timePass", userInfo: nil, repeats: true)
    timer.fire()
}

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

func timePass() {
    
    let _time = NSDate().timeIntervalSinceDate(expectedTime)
    let timeIsOut = _time >= 0
    
    ccRight(_time)
    if Int(-_time) == 300 {
        delegate?.PreviewCountdownLabelCorrectTime()   //当倒计时还剩余五分钟时,去服务器重新获取时间,校准倒计时时间
    }
    if timeIsOut {
        font(UIFont(name: "Quartz-Regular", size: 20)!)
        text("00:00:00")
        guard isFirst == 0 else {
            timer.invalidate()
            delegate?.PreviewCountdownLabelExhaust()    //当倒计时完成后走这个代理方法,去改变布局UI
            return
        }
        isFirst = 1
        
        } else {
            let time = NSDate(timeIntervalSince1970: 0).dateByAddingTimeInterval(-_time - timet)
            let str = PreviewCountdownLabel.preTimeFormatter.stringFromDate(time)
            font(UIFont(name: "Quartz-Regular", size: 20)!)
            text("\(str)")
        }
    }

 }

然后在需要实现代理方法的类中去遵守代理协议,实现代理方法

MARK: - Methods
extension TaskDetailViewController {

func closeButtonClick() {
    dismissViewControllerAnimated(true, completion: nil)
}

func askTaskInfo() {
    API.taskDetail(self.taskID) { task in
        ccRight(self.taskID)
        
        self._task = task
        self.discountRateL.text(task.selfBuyOff.string)
        self.addressL.text(task.areaDisplayName)
        self.priceL.text(task.price.string)
        self.commissionL.text(task.shotFee.string)
        self.orderNameLabel.text(task.title)
        self.requisitionLabel.text(task.shortDescription)
        self.imageURL = task.imageURLString
        self.imageView.kf_setImageWithURL(task.imageURLString.URL, placeholderImage: AppStyle.PlaceHolderImage)
        self.displayStatus = task.relation
        let time1 = NSDate(jsonDate: "/Date(" + task.databaseTime + "+0800)/")
        let time2 = NSDate(jsonDate: "/Date(" + task.futurePublishTime + "+0800)/")
        let time = NSTimeInterval(task.diffTime)
        
        
        
        ccRight(time1)
        ccRight(time2)
        
        if task.isTimerTask == .YES {
            
            if time > 0 {
                if self.countDownLabel == nil {
                    self.countDownLabel = PreviewCountdownLabel()
                        .superView(self.view)
                        .width(98)
                        .bottom(170 + 49 + 5)
                        .right(12)
                        .height(28)
                        .backgroundColor(UIColor.blackColor().alpha(0.5))
                        .textAlignmentCenter()
                        .cornerRadius(6)
                }
                
                self.countDownLabel!.delegate = self
                self.countDownLabel!.hidden = false
                self.countDownLabel!.expectedTime = NSDate().dateByAddingTimeInterval(time! / 1000)
            }
            // 预览  查看任务要求(倒计时完后,显示抢单,可选择继续抢单,或者跳转H5查看任务要求)
            switch task.isCustomTask {
            case .No:
                self.getOrderButton.title("预览")
                self.getOrderButton.removeTarget(self, action: "getOrderButtonClick", forControlEvents: UIControlEvents.AllEvents)
                self.getOrderButton.removeTarget(self, action: "PreviewAction", forControlEvents: UIControlEvents.AllEvents)
                self.getOrderButton.target(self, upInsideAction: "PreviewAction")
                self.getOrderButton.enabled(true)
                AnimateWithDuration(0.15) {
                    self.getOrderButton.backgroundColor(AppStyle.Tint)
                }
                ccRight("不是")
            case .Yes:
                self.getOrderButton.title("查看任务要求")
                self.getOrderButton.removeTarget(self, action: "getOrderButtonClick", forControlEvents: UIControlEvents.AllEvents)
                self.getOrderButton.removeTarget(self, action: "PreviewAction", forControlEvents: UIControlEvents.AllEvents)
                self.getOrderButton.target(self, upInsideAction: "PreviewAction")
                self.getOrderButton.enabled(true)
                AnimateWithDuration(0.15) {
                    self.getOrderButton.backgroundColor(AppStyle.Tint)
                }
                ccRight("是")
            }
        }else {
            self.getOrderButton.title("抢单")
            if task.relation == Task.RelationToToken.Accepted || task.isDirect == Task.DirectionalPush.Yes{
                self.getOrderButton.removeTarget(self, action: "getOrderButtonClick", forControlEvents: UIControlEvents.AllEvents)
                self.getOrderButton.removeTarget(self, action: "PreviewAction", forControlEvents: UIControlEvents.AllEvents)
                self.getOrderButton.target(self, upInsideAction: "getOrderButtonClick")
                self.getOrderButton.enabled(true)
                AnimateWithDuration(0.15) {
                    self.getOrderButton.backgroundColor(AppStyle.Tint)
                }
            }else {
                if task.relation == Task.RelationToToken.UnAccepted ||  task.relation == Task.RelationToToken.Finished {
                    self.getOrderButton.enabled(true)
                    AnimateWithDuration(0.15) {
                        self.getOrderButton.backgroundColor(AppStyle.GrayTextColor)
                    }
                }
            }
        }
    }
}

初始化好了自定义倒计时Label,设置好代理然后实现协议方法:

   MARK: - PreviewCountdownLabelDelegate
   extension TaskDetailViewController : PreviewCountdownLabelDelegate {

   func PreviewCountdownLabelCorrectTime() {
            askTaskInfo()
    }

  func PreviewCountdownLabelExhaust() {
          self.countDownLabel!.hidden = true
          self.countDownLabel!.timer.invalidate()
          askTaskInfo()
    }
}

你可能感兴趣的:(Swift之代理实现)