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

效果图


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

相关推荐
linweidong2 小时前
美团ios开发100道面试题及参考答案(下)
objective-c·swift·jspatch·ios开发·ios面试·ios面经·xcode调试
__WanG1 天前
screen time api - FamilyActivityPicker 获取选中应用
ios·iphone·swift
东坡肘子2 天前
Swift、SwiftUI 与 SwiftData:走向成熟的 2025 -- 肘子的 Swift 周报 #116
人工智能·swiftui·swift
大熊猫侯佩3 天前
Swift 6.2 列传(第十三篇):香香公主的“倾城之恋”与优先级飞升
swift·编程语言·apple
1024小神3 天前
Swift配置WKwebview加载网站或静态资源后,开启调试在电脑上debug
swift
kkoral4 天前
基于MS-Swift 为 Qwen3-0.6B-Base 模型搭建可直接调用的 API 服务
python·conda·fastapi·swift
Yorelee.5 天前
ms-swift在训练时遇到的部分问题及解决方案
开发语言·nlp·transformer·swift
崽崽长肉肉6 天前
swift中的知识总结(一)
ios·swift
Yakamoz6 天前
Swift Array的写时复制
swift
汉秋6 天前
SwiftUI 中的 compositingGroup():真正含义与渲染原理
swiftui·swift