带有叠加层的活动指示器





5.00/5 (5投票s)
如何显示带有叠加层的活动指示器
在任务进行中为用户提供视觉提示是一项常见任务。Apple UIKit 具有 UIActivityIndicatorView UI 组件来实现此目的。该组件显示一个旋转或停止的“齿轮” 。 在本文中,我们将扩展它
- 在整个屏幕或屏幕的一部分上显示一个透明的叠加层。叠加层将阻止用户与覆盖的控件交互,同时任务正在进行中。
- 在叠加层的中心以编程方式创建动画
UIActivityIndicatorView
,以指示正在处理任务。 - 在叠加层中显示附加文本,以提供更多信息。
创建叠加层
我们将叠加层作为 UIView
控制创建。
叠加层的框架大小将与它覆盖的目标相同。
let overlay = UIView(frame: overlayTarget.frame)
通过将其中心设置为与其目标相同,将叠加层定位为完全覆盖其目标。
overlay.center = overlayTarget.center
最初将叠加层的 alpha 设置为 0(完全透明)。 稍后我们将逐渐将其更改为 0.5,以动画显示叠加层。
overlay.alpha = 0
overlay.backgroundColor = UIColor.blackColor()
将叠加层添加到其目标。 将叠加层置于最前面,以确保它覆盖目标并阻止用户与目标上的其他控件交互。
overlayTarget.addSubview(overlay)
overlayTarget.bringSubviewToFront(overlay)
通过逐渐更改 alpha 值来动画显示叠加层。
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.5)
overlay.alpha = overlay.alpha > 0 ? 0 : 0.5
UIView.commitAnimations()
创建 UIActivityIndicatorView
let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
indicator.center = overlay.center
indicator.startAnimating()
overlay.addSubview(indicator)
创建加载文本标签
当提供加载文本时,我们将创建一个 UILabel
来显示它。 我们调用 sizeToFit 来调整标签大小以适应文本。 我们将标签定位在叠加层中的 UIActivityIndicatorView
正下方。
if let textString = loadingText {
let label = UILabel()
label.text = textString
label.textColor = UIColor.whiteColor()
label.sizeToFit()
label.center = CGPoint(x: indicator.center.x, y: indicator.center.y + 30)
overlay.addSubview(label)
}
使用方法
包含 LoadingIndicatorView.swift 文件。
在长时间运行的任务之前,调用其中一个 show()
方法来显示加载指示器。
// Show indicator to cover entire screen
LoadingIndicatorView.show()
// Show indicator to cover entire screen with custom text
LoadingIndicatorView.show("Loading")
// Show indicator to cover target view
LoadingIndicatorView.show(target)
// Show indicator to cover target view with custom text
LoadingIndicatorView.show(target, "Loading")
在长时间运行的任务之后,调用 hide()
方法来隐藏加载指示器。
LoadingIndicatorView.hide()