开发过程中,我们经常要用到弹框作为提示框,有时系统默认的弹款不能满足我们的需求,这时就需要我们自己自定义,在弹框出来的时候给它一个动画效果,将视图背景设置为半透明,效果如下:
代码如下:
自定义的弹框view
import UIKit
class ShowView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.black.withAlphaComponent(0.5)
let button = UIButton.init(frame: .init(x: 0, y: 0, width: 200, height: 200))
button.backgroundColor = UIColor.green
button.setTitle("自定义的弹框", for: .normal)
button.center = self.center
button.addTarget(self, action: #selector(removeAction(sender:)), for: .touchUpInside)
self.addSubview(button)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: 弹框动画
func animationWithAlertViewWithView() {
var animation: CAKeyframeAnimation?
animation = CAKeyframeAnimation(keyPath: "transform")
animation?.duration = 0.2
animation?.isRemovedOnCompletion = true
animation?.fillMode = .forwards
var values: [AnyHashable] = []
values.append(NSValue(caTransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)))
values.append(NSValue(caTransform3D: CATransform3DMakeScale(1.1, 1.1, 1.0)))
values.append(NSValue(caTransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)))
animation?.values = values
self.layer.add(animation!, forKey: nil)
}
//MARK: 移除弹框
@objc func removeAction(sender:UIButton) {
self.removeFromSuperview()
}
}
ViewController
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton.init(frame: .init(x: 0, y: 0, width: 50, height: 50))
button.backgroundColor = UIColor.red
button.setTitle("弹框", for: .normal)
button.center = self.view.center
button.addTarget(self, action: #selector(showAction), for: .touchUpInside)
self.view.addSubview(button)
}
@objc func showAction() {
let showView = ShowView.init(frame: self.view.bounds)
self.view.window?.addSubview(showView)
showView.animationWithAlertViewWithView()
}
}