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

效果图


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

相关推荐
东坡肘子1 天前
Macbook Neo:苹果重回校园的起点 -- 肘子的 Swift 周报 #126
人工智能·swiftui·swift
TT_Close6 天前
【Flutter×鸿蒙】FVM 不认鸿蒙 SDK?4步手动塞进去
flutter·swift·harmonyos
张江6 天前
Swift Concurrency学习
swift
东坡肘子8 天前
OpenClaw 不错,但我好像没有那么需要 -- 肘子的 Swift 周报 #125
人工智能·swiftui·swift
Swift社区13 天前
LeetCode 391 完美矩形 - Swift 题解
算法·leetcode·swift
升讯威在线客服系统14 天前
从 GC 抖动到稳定低延迟:在升讯威客服系统中实践 Span 与 Memory 的高性能优化
java·javascript·python·算法·性能优化·php·swift
Swift社区14 天前
LeetCode 390 消除游戏 - Swift 题解
leetcode·游戏·swift
东坡肘子15 天前
春晚、机器人、AI 与 LLM -- 肘子的 Swift 周报 #124
人工智能·swiftui·swift
BatmanWayne18 天前
swift-微调补充
人工智能·swift
疯笔码良22 天前
【swiftUI】实现自定义的底部TabBar组件
ios·swiftui·swift