悬浮按钮

//创建一个继承于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隐藏


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值