代码如下:
调用方法:
SwiftNoticeDemo.noticeOnStatusBar("你好么", autoClear: true, autoClearTime: 2)
SwiftNoticeDemo.swift代码如下:
import Foundation
import UIKit
class SwiftNoticeDemo:NSObject {
static var windows = [UIWindow]()
@discardableResult
static func noticeOnStatusBar(_ text:String,autoClear:Bool,autoClearTime:Int) -> UIWindow {
let frame = UIApplication.shared.statusBarFrame
let window = UIWindow()
window.backgroundColor = UIColor.purple
let view = UIView()
view.backgroundColor = UIColor.red
let label = UILabel(frame: frame.height > 20 ? CGRect(x: frame.origin.x, y: frame.origin.y + frame.height - 17, width: frame.width, height: 20):frame)
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 12)
label.textColor = UIColor.white
label.text = text
view.addSubview(label)
window.frame = frame
view.frame = frame
window.windowLevel = UIWindowLevelAlert
window.isHidden = false
window.addSubview(view)
windows.append(window)
var orgPoint = view.frame.origin
orgPoint.y = -(view.frame.size.height)
let destPoint = view.frame.origin
view.frame = CGRect(origin: orgPoint, size: view.frame.size)
UIView.animate(withDuration: 0.7, animations: {
view.frame = CGRect(origin: destPoint, size: view.frame.size)
}) { (true) in
if autoClear {
self.perform(.hideNotice, with: window, afterDelay: TimeInterval(autoClearTime))
}
}
return window
}
}
fileprivate extension Selector {
static let hideNotice = #selector(SwiftNoticeDemo.hideNotice(_:))
}
@objc extension SwiftNoticeDemo {
static func hideNotice(_ sender:AnyObject) {
if let window = sender as? UIWindow {
if let view = window.subviews.first {
UIView.animate(withDuration: 0.8, animations: {
view.frame = CGRect(x: 0, y: -view.frame.height, width: view.frame.width, height: view.frame.height)
view.alpha = 0
}) { boo in
if let index = windows.index(where:{(item) -> Bool in
return item == window
}) {
windows.remove(at: index)
}
}
}
}
}
}