Swift 는 iOS 응용 프로그램 에서 문자 인증 코드 카운트다운 기능 의 인 스 턴 스 공 유 를 실현 합 니 다.
속성 관찰 기 는 속성 값 의 변 화 를 감시 하고 응답 합 니 다.속성 이 설정 되 어 있 을 때마다 속성 관찰 기 를 호출 합 니 다.심지어 새로운 값 이 현재 값 과 같 을 때 도 예외 가 아 닙 니 다.
속성 에 다음 과 같은 하나 또는 모든 관찰 기 를 추가 할 수 있 습 니 다:
먼저 보 내기 단 추 를 설명 합 니 다:
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
}
완성!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
View의 레이아웃 방법을 AutoLayout에서 따뜻한 손 계산으로 하면 성능이 9.26배로 된 이야기이 기사는 의 15 일째 기사입니다. 어제는 에서 이었습니다. 손 계산을 권하는 의도는 없고, 특수한 상황하에서 계측한 내용입니다 화면 높이의 10 배 정도의 contentView가있는 UIScrollView 레이아...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.