Swift 는 iOS 응용 프로그램 에서 문자 인증 코드 카운트다운 기능 의 인 스 턴 스 공 유 를 실현 합 니 다.

3750 단어 인증번호Swift
시작 하기 전에 개념 속성 관측 기(Property Observer)를 알 아 보 겠 습 니 다.
속성 관찰 기 는 속성 값 의 변 화 를 감시 하고 응답 합 니 다.속성 이 설정 되 어 있 을 때마다 속성 관찰 기 를 호출 합 니 다.심지어 새로운 값 이 현재 값 과 같 을 때 도 예외 가 아 닙 니 다.
속성 에 다음 과 같은 하나 또는 모든 관찰 기 를 추가 할 수 있 습 니 다:
  • willSet 은 새로운 값 이 설정 되 기 전에 호출 됩 니 다
  • didSet 는 새로운 값 이 설 정 된 후에 바로 호출 합 니 다
  • 다음은 우리 의 튜 토리 얼 을 시작 하여 최종 효 과 를 보 여 드 리 겠 습 니 다.
    2016418144945893.gif (372×180)
    먼저 보 내기 단 추 를 설명 합 니 다:

    var sendButton: UIButton!
    viewdLoad 방법 에서 보 내기 버튼 에 속성 추가:

    override func viewDidLoad() {
        super.viewDidLoad()

        sendButton = UIButton()
        sendButton.frame = CGRect(x: 40, y: 100, width: view.bounds.width - 80, height: 40)
        sendButton.backgroundColor = UIColor.redColor()
        sendButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        sendButton.setTitle(" ", forState: .Normal)
        sendButton.addTarget(self, action: "sendButtonClick:", forControlEvents: .TouchUpInside)

        self.view.addSubview(sendButton)
    }

    다음은 변 수 를 설명 합 니 다.remaining Seconds 는 현재 카운트다운 남 은 초 수 를 대표 합 니 다.

    var remainingSeconds = 0
    우 리 는 remaining Seconds 에 willSet 방법 을 추가 합 니 다.이 방법 은 remaining Seconds 의 값 이 변 할 때 호출 되 고 값 을 매개 변수 new Value 에 전달 합 니 다.

    var remainingSeconds: Int = 0 {
        willSet {
            sendButton.setTitle(" (\(newValue) )", forState: .Normal)

            if newValue <= 0 {
                sendButton.setTitle(" ", forState: .Normal)
                isCounting = false
            }
        }
    }

    remaining Seconds 가 변 할 때 sendButton 의 디 스 플레이 텍스트 를 업데이트 합 니 다.
    카운트다운 기능 은 NSTimer 로 이 루어 집 니 다.먼저 NSTimer 인 스 턴 스 를 설명 합 니 다.

    var countdownTimer: NSTimer?
    그리고 카운트다운 을 켜 고 닫 는 변 수 를 설명 합 니 다.

    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTime", userInfo: nil, repeats: true)

                remainingSeconds = 10
                sendButton.backgroundColor = UIColor.grayColor()
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil

                sendButton.backgroundColor = UIColor.redColor()
            }

            sendButton.enabled = !newValue
        }
    }

    마찬가지 로,우 리 는 isCounting 에 willSet 방법 을 추가 합 니 다.isCounting 의 new Value 가 true 일 때,우 리 는 NSTimer 의 클래스 방법 을 호출 합 니 다.
    scheduled Timer WithTimeInterval:target:selector:userInfo:repeats:방금 설명 한 countdownTimer 인 스 턴 스 를 만 들 고 시작 합 니 다.이 인 스 턴 스 는 매 초 마다 updateTime:방법 을 호출 합 니 다.

    func updateTime(timer: NSTimer) {
         // , remainingSeconds
        remainingSeconds -= 1
    }
    isCounting 의 new Value 가 false 일 때,countdown Timer 를 멈 추고 countdown Timer 를 nil 로 설정 합 니 다.
    또한 카운트다운 시간(여 기 는 프레젠테이션 시간 을 5 초 로 설정 합 니 다)과 보 내기 단 추 를 서로 다른 isCounting 상태 에서 스타일(배경 색 조정)과 클릭 할 수 있 는 지 여 부 를 설정 합 니 다.
    마지막 으로 sendButton Click:방법 을 실현 합 니 다.이 방법 은 sendButton 을 클릭 할 때 호출 합 니 다.

     func sendButtonClick(sender: UIButton) {
        //
        isCounting = true
    }
    완성!

    좋은 웹페이지 즐겨찾기