//创建一个继承于UIWindow的类,用于显示悬浮按钮
import UIKit
class AssistiveTouch: UIWindow {
var button:UIButton!
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
self.windowLevel = UIWindowLevelAlert + 1
//这句话很重要
self.makeKeyAndVisible()
button = UIButton.init(type: .custom)
button.backgroundColor = UIColor.gray
button.frame = self.bounds
button.layer.cornerRadius = self.frame.size.width/2
self.addSubview(button)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//AppDelegate如下设置
var window: UIWindow?
var win:AssistiveTouch!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// 这句话很重要,要先将rootview加载完成之后在显示悬浮框,如没有这句话,将可能造成程序崩溃
self.perform(#selector(AppDelegate.setNav), with: nil, afterDelay: 1.0)
self.window?.makeKeyAndVisible()
return true
}
//悬浮按钮点击事件
func choose(sender:UIButton) {
let story = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "MainViewController")
(self.window?.rootViewController as! UINavigationController).pushViewController(story, animated: true)
/*注意:如果Controller有带UINavigationController,必须添加as UINavigationController,否则直接self.window?.rootViewController*/
//self.window?.rootViewController?.present(story, animated: true, completion: nil)
}
func setNav() {
win = AssistiveTouch.init(frame: CGRect.init(x: 100, y: 100, width: 100, height: 100))
win.button.addTarget(self, action: #selector(choose(sender:)), for: .touchUpInside)
}
备注:由于悬浮按钮默认情况下是一直悬停的,如果在某些页面上不需要显示,则调用
(UIApplication.shared.delegate as! AppDelegate).win.isHidden = true隐藏