「SwiftUI」底部弹窗弹出和收起

前言:通常在一些页面会用到底部弹窗,进行一些数据展示或二次确认。
页面编写思路:
  1. 编写弹窗View
  2. 在VC控制器中对于弹窗进行弹起和收起操作

弹窗弹起和收起代码

swift 复制代码
// MARK: - 平移动画
/// 向上平移
func toUpTranslation(targetView: UIView, y: CGFloat) {
    let animation = CABasicAnimation(keyPath: "position")
    /// 开始的位置
    animation.fromValue = CGPoint(x: targetView.layer.position.x, y: targetView.layer.position.y)
    /// 移动到的位置
    animation.toValue = CGPoint(x: targetView.layer.position.x, y: y)
    
    /// 动画持续时间
    animation.duration = 0.3
    /// 动画填充模式
    animation.fillMode = .forwards
    /// 动画完成不删除
    animation.isRemovedOnCompletion = false
    
    /// 添加动画
    targetView.layer.add(animation, forKey: "animation")
    
    /// 重新设置坐标
    targetView.center = CGPoint(x: targetView.layer.position.x, y: y)
}

/// 向下平移
func toDownTranslation(targetView: UIView, y: CGFloat) {
    let animation = CABasicAnimation(keyPath: "position")
    /// 开始的位置
    animation.fromValue = CGPoint(x: targetView.layer.position.x, y: targetView.layer.position.y)
    /// 移动到的位置
    animation.toValue = CGPoint(x: targetView.layer.position.x, y: y)
    
    /// 动画持续时间
    animation.duration = 0.3
    /// 动画填充模式
    animation.fillMode = .forwards
    /// 动画完成不删除
    animation.isRemovedOnCompletion = false
    
    /// 添加动画
    targetView.layer.add(animation, forKey: "animation")
    
    /// 重新设置坐标
    targetView.center = CGPoint(x: targetView.layer.position.x, y: y)
}

注意:该方法中的y点是指弹窗中心点移动到的y轴位置

代码使用方法:

swift 复制代码
private var alertView: AlertView!

private func initView() {
	alertView = AlertView(frame: CGRect(x: 0, y: Common.screenHeight, width: Common.screenWidth, height: 432.fit()))
	alertView.sureButtonAction = {
	self.toDownTranslation(targetView: self.alertView, y: Common.screenHeight + self.alertView.height/2)
	}

	self.view.addSubview(alertView)
}

private func clickToUpAlert() {
	self.toUpTranslation(targetView: self.alertView, y: Common.screenHeight - self.alertView.height/2)
}

该方法使用过程中需注意:弹窗初设frame时的y是指弹窗的左上点,弹窗上下移动方法中的y是指弹窗中心点移动到的位置

效果图


整理不易,望大家多多点赞,谢谢大家!

相关推荐
2501_915909061 天前
SwiftUI 和 UIKit 怎么选?两代 UI 框架的适用范围
vscode·ios·objective-c·个人开发·swift·敏捷流程
2501_915918411 天前
在Windows10上使用VSCode和Code Runner搭建Swift开发环境详细步骤
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
用户468104557242 天前
Swift 异步与并发
swift
安当加密03012 天前
PCI DSS 4.0与SWIFT CSP双合规:银行收单与跨境支付HSM部署实战
swift·hsm·密钥管理·pci dss·双合规
麒麟马3 天前
Swift 扩展归纳---Array (一)
ios·swift
2501_915106323 天前
Swift 4开发环境设置教程:xCode安装与Playground入门
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
东坡肘子4 天前
当 Mac mini 的价格不再 mini -- 肘子的 Swift 周报 #152
人工智能·swiftui·swift
2501_915106327 天前
第一次开发 iPhone App,可能碰到的问题,解决办法
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
末代iOS程序员华仔8 天前
iOS 5.6 条例解决方法
flutter·ios·swift
末代iOS程序员华仔8 天前
Guideline 5.6 - Developer Code of Conduct
flutter·ios·swift