UIActivityIndicatorView 動態指示器
宣告資料
var circle = UIActivityIndicatorView()
var btn = UIButton()
var timer = Timer()
var count: Int = 0
let WIDTH = UIScreen.main.bounds.size.width
viewDidLoad
背景顏色
view.backgroundColor = .lightGray
UIActivityIndicatorView
// 指示器樣式 circle = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) /* UIActivityIndicatorViewStyle .whiteLarge .white .gray */ // 中心點 circle.center = CGPoint(x: WIDTH / 2, y: 205) // 動態指示器顏色 circle.color = .blue // 背景顏色 circle.backgroundColor = .clear // 完成後隱藏 //circle.hidesWhenStopped = false view.addSubview(circle)
UIButton(觸發UIActivityIndicatorView)
btn.frame.size = CGSize(width: 60, height: 60) btn.center = CGPoint(x: WIDTH / 2, y: 205) btn.setTitle("執行", for: .normal) btn.backgroundColor = .blue btn.layer.cornerRadius = 30 btn.addTarget(self, action: #selector(btnpressed), for: .touchDown) view.addSubview(button)
讀取動作
func btnpressed(sender: UIButton) {
// 指示器開始動作
circle.startAnimating()
// 建立計時器
timer = Timer.scheduledTimer(timeInterval: 0.1,
target: self,
selector: #selector(timeron),
userInfo: [],
repeats: true)
UIView.animate(withDuration: 0.3,
delay: 0,
options: [.curveEaseInOut],
animations: { () -> Void in
self.circle.center = CGPoint(x: self.WIDTH / 2,
y: 75)
self.btn.setTitle("",
for: .normal)
self.btn.backgroundColor = .red
},
completion: nil)
}
計時器動作
func timeron(sender: Timer) {
// 每回增加1點
count += 1
// 全滿40 點
let complete = 40
let btnwidth = abs(abs(count - 20) * 6 - 60)
let btnheight = abs(abs(count - 20) * 6 - 60)
btn.frame.size = CGSize(width: btnwidth,
height: btnheight)
btn.center = CGPoint(x: WIDTH / 2,
y: 205)
btn.layer.cornerRadius = CGFloat(abs(abs(count - 20) * 6 - 60) / 2)
if count == complete {
// 計數歸零
count = 0
// 指示器停止動作
circle.stopAnimating()
// 計時器停止動作
timer.invalidate()
UIView.animate(withDuration: 0.3,
delay: 0,
options: [.curveEaseInOut],
animations: { () -> Void in
self.circle.center = CGPoint(x: self.WIDTH / 2,
y: 205)
self.btn.frame.size = CGSize(width: 60,
height: 60)
self.btn.setTitle("執行",
for: .normal)
self.btn.backgroundColor = .blue
self.btn.layer.cornerRadius = 30
},
completion: nil)
}
}
下載完整範例 OneDrive