Lennakim

I am lennakim

0%

尝试用swift写一个ios app demo

10-1假期, 闲来无事, 写了个计时器.
之前没有 object-c, swift 经验, 基本是依葫芦画瓢.

教程Jason编写的, 很详细,另外有一个bug, Jason希望大家能发现, 并帮他修复. 感觉这种发现问题的方式很不错丫.

核心是一个 CounterViewController.swift 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218

import UIKit

class CounterViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()

setupTimeLabel()
setuptimeButtons()
setupActionButtons()

remainingSeconds = 0
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()

timeLabel!.frame = CGRectMake(10, 40, self.view.bounds.size.width-20, 120)

let gap = ( self.view.bounds.size.width - 10*2 - (CGFloat(timeButtons!.count) * 64) ) / CGFloat(timeButtons!.count - 1)

for (index, button) in enumerate(timeButtons!) {
let buttonLeft = 10 + (64 + gap) * CGFloat(index)

button.frame = CGRectMake(buttonLeft, self.view.bounds.size.height-120, 64, 44)
}

startStopButton!.frame = CGRectMake(10, self.view.bounds.size.height - 60, self.view.bounds.size.width-20-120, 44)

clearButton!.frame = CGRectMake(10+self.view.bounds.size.width-20-100+20, self.view.bounds.size.height-60, 80, 44)
}

///UI Element
var timeLabel: UILabel? //显示剩余时间
var timeButtons: [UIButton]? //设置时间的按钮数组
var startStopButton: UIButton? //启动/停止按钮
var clearButton: UIButton? //复位按钮
let timeButtonInfos = [("1分", 60), ("3分", 180), ("5分", 300), ("秒", 1)]


//启动或停止倒计时
//使用Swift的方式来解决状态跟UI的同步问题:使用属性的willSet或didSet方法
var isCounting: Bool = false {
willSet(newValue) {
if newValue {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTimer:", userInfo: nil, repeats: true)
} else {
timer?.invalidate()
timer = nil
}

setSettingButtonsEnabled(!newValue)
}
}

var timer: NSTimer? // 设置定时器

//使用Swift的方式来解决状态跟UI的同步问题:使用属性的willSet或didSet方法
var remainingSeconds: Int = 0 {

willSet(newSeconds) {
let mins = newSeconds / 60
let seconds = newSeconds % 60

timeLabel!.text = NSString(format: "%02d:%02d", mins, seconds)

if newSeconds <= 0 {
isCounting = false
startStopButton!.alpha = 0.3
startStopButton!.enabled = false
} else{
startStopButton!.alpha = 1.0
startStopButton!.enabled = true
}
}
}

//UI Controls

func setupTimeLabel() {
timeLabel = UILabel()
timeLabel!.textColor = UIColor.whiteColor()
timeLabel!.font = UIFont(name: "Helvetica", size: 80)
timeLabel!.backgroundColor = UIColor.blackColor()
timeLabel!.textAlignment = NSTextAlignment.Center

self.view.addSubview(timeLabel!)
}

func setuptimeButtons() {
var buttons: [UIButton] = []

for (index, (title, _)) in enumerate(timeButtonInfos) {

let button: UIButton = UIButton()
button.tag = index //保存按钮的index
button.setTitle("\(title)", forState: UIControlState.Normal)

button.backgroundColor = UIColor.orangeColor()
button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Highlighted)

button.addTarget(self, action: "timeButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)

buttons += [button]
self.view.addSubview(button)

}

timeButtons = buttons
}

func setupActionButtons() {
//create start/stop button

startStopButton = UIButton()

startStopButton!.setTitle("启动/停止", forState: UIControlState.Normal)

startStopButton!.backgroundColor = UIColor.redColor()

startStopButton!.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)

// 为button绑定TouchUpInside事件
startStopButton!.addTarget(self, action: "startStopButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)

self.view.addSubview(startStopButton!)

/////////////////////clearButton/////////////////////

clearButton = UIButton()

clearButton!.setTitle("复位", forState: UIControlState.Normal)

clearButton!.backgroundColor = UIColor.redColor()

clearButton!.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)

clearButton!.setTitleColor(UIColor.blackColor(), forState: UIControlState.Highlighted)

clearButton!.addTarget(self, action: "clearButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)

self.view.addSubview(clearButton!)

}

///Actions & Callbacks
func startStopButtonTapped(sender: UIButton) {
isCounting = !isCounting //切换了isCounting的状态

if isCounting {
createAndFireLocalNotificationAfterSeconds(remainingSeconds)
} else {
UIApplication.sharedApplication().cancelAllLocalNotifications()
}
}

func clearButtonTapped(sender: UIButton) {
remainingSeconds = 0 //复位按钮将时间置0
}

//累加时间
func timeButtonTapped(sender: UIButton) {
let (_, seconds) = timeButtonInfos[sender.tag]
remainingSeconds += seconds
}

func updateTimer(timer: NSTimer) {
remainingSeconds -= 1

// 弹出警告窗口,提示倒计时完成
if remainingSeconds <= 0 {
let alert = UIAlertView()

alert.title = "计时完成"
alert.message = ""
alert.addButtonWithTitle("OK")
alert.show()
}
}

///

func setSettingButtonsEnabled(enabled: Bool) {
for button in timeButtons! {
button.enabled = enabled
button.alpha = enabled ? 1.0 : 0.3
}

clearButton!.enabled = enabled
clearButton!.alpha = enabled ? 1.0 : 0.3
}

//注册系统通知
func createAndFireLocalNotificationAfterSeconds(seconds: Int) {

UIApplication.sharedApplication().cancelAllLocalNotifications()
let notification = UILocalNotification()

let timeIntervalSinceNow = Double(seconds)

notification.fireDate = NSDate(timeIntervalSinceNow:timeIntervalSinceNow);

notification.timeZone = NSTimeZone.systemTimeZone()
notification.alertBody = "计时完成!"

UIApplication.sharedApplication().scheduleLocalNotification(notification)

}

}

从 simulator上测试, 到真机上运行, 花了很多时间, 要申请开发者, 要 bundle id, 下载开发者证书 …
各种东西,步骤已经忘了, 现在没时间折腾了.

效果如下: