「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是指弹窗中心点移动到的位置

效果图


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

相关推荐
人月神话-Lee21 小时前
【图像处理】Core Image 与 GPU 渲染管线——让滤镜飞起来
图像处理·人工智能·ios·chatgpt·ai编程·swift·gpu
夏天的峰没有风1 天前
Typora+gitcode+picgo搭建免费图床
开发语言·ios·swift
sakiko_2 天前
Swift学习笔记34-MVC架构,SwiftUI与UIkit混编练习
笔记·学习·swiftui·mvc·swift
sakiko_2 天前
Swift学习笔记35-本地化
笔记·学习·swift
光电的一只菜鸡3 天前
shell脚本开发技巧
开发语言·ios·swift
人月神话-Lee3 天前
【图像处理】框架设计——协议、值类型与工程化思维
图像处理·人工智能·ios·设计模式·架构·ai编程·swift
人月神话-Lee4 天前
【图像处理】图像导出与工业级压缩策略——从像素到文件的最后一公里
图像处理·人工智能·ios·ai编程·swift
iOS日常4 天前
iOS 横竖屏实践(UIKit)
swift
看谷秀4 天前
wift Part 5 oc -> swift
swift
sakiko_4 天前
Swift学习笔记33-多线程与UI渲染
笔记·学习·swiftui·swift