在开发过程中,我们经常用到弹框,但是系统提供的弹框并不能完成我们的样式需求,这个时候我们就需要自定义弹框,但是当我们使用纯代码写弹框太过麻烦,而且效果展示不出来,需要每次运行程序才能看到,所以我们就需要通过Xib直接拖拽来实现,下面就是通过代码来实现自定义弹框
第一步、创建自定义View
第二步、就是创建对应的Xib
第三步、给Xib取名字,最好和上面创建的View一样
第四步、Xib与View关联
第五步、此时AlertView.Xib中是没有View,我们拖拽一个UIView
第六步、将Xib中拖拽的View连接到AlertView.swift文件中,名字随便(这里命名为contentView)
第七步、接着将上面的contentView代码添加到AlertView.swift上
override init(frame: CGRect) { super.init(frame: frame) // 加载xib,loadNibNamed("xib的名称") contentView = (Bundle.main.loadNibNamed("AlertView", owner: self, options: nil)?.last as! UIView) // 设置frame contentView.frame = frame contentView.backgroundColor = UIColor.black.withAlphaComponent(0.5) NSToolObjectClass.animationWithAlertViewWithView(allView: tipView) // 添加上去 addSubview(contentView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }这样就将Xib的View效果添加到了AlertView上,剩下的就是讲所需要的画面在Xib上布局即可了
下面是效果图,在项目随便一个也面写的
下面是使用代码
let alertView = AlertView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)) alertView.messageLabel.text = "你确定要退出登录吗?" alertView.changeBlock = { index in print(index) } self.view.addSubview(alertView)GitHub下载地址:https://github.com/WangQingLei307909/walertview/blob/master/AlertView.zip