- 创建一个新的UIWindow并将其添加到应用程序的主窗口上方:
let window = UIWindow(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
window.windowLevel = .statusBar + 1
window.backgroundColor = UIColor.clear
window.makeKeyAndVisible()
UIApplication.shared.windows.first?.addSubview(window)
- 创建一个UILabel来显示文本内容,并设置相关属性:
let label = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
label.text = "这里是提词器的文本内容"
label.font = UIFont.systemFont(ofSize: 16)
label.textColor = UIColor.white
label.numberOfLines = 0
label.textAlignment = .center
self.view.addSubview(label)
- 实现拖动和缩放悬浮窗口的功能:
@IBAction func panGestureAction(_ sender: UIPanGestureRecognizer) {
let point = sender.translation(in: self.view.superview)
sender.setTranslation(CGPoint.zero, in: self.view.superview)
var center = self.view.center
center.x += point.x
center.y += point.y
self.view.center = center
}
@IBAction func pinchGestureAction(_ sender: UIPinchGestureRecognizer) {
if sender.state == .began || sender.state == .changed {
let scale = sender.scale
self.view.transform = self.view.transform.scaledBy(x: scale, y: scale)
sender.scale = 1.0
}
}
- 使用Auto Layout进行布局:
self.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.view.topAnchor.constraint(equalTo: self.view.superview!.topAnchor),
self.view.leadingAnchor.constraint(equalTo: self.view.superview!.leadingAnchor),
self.view.trailingAnchor.constraint(equalTo: self.view.superview!.trailingAnchor),
self.view.bottomAnchor.constraint(equalTo: self.view.superview!.bottomAnchor)
])