如何将Swift的UIViewController扩展独立为文件实现跨控制器复用
操作步骤
- 第一步:新建Swift文件,命名遵循扩展类目标记规范,推荐命名为
UIViewController+Toast.swift,方便快速识别文件作用 - 第二步:在新建的文件中写入如下代码,注意必须导入UIKit依赖才能调用UI相关组件:
import UIKit extension UIViewController { func showToast(message: String){ let toast = UILabel(frame: CGRect( x: self.view.frame.width/2-75, y: self.view.frame.height - 100, width: 150, height: 40)) toast.textAlignment = .center toast.backgroundColor = .label toast.textColor = .systemBackground toast.alpha = 1.0 toast.layer.cornerRadius = 10 toast.clipsToBounds = true toast.text = message self.view.addSubview(toast) UIView.animate( withDuration: 4.0, delay: 1.0, options: .curveEaseInOut, animations: { toast.alpha = 0.0 }) { (isCompleted) in toast.removeFromSuperview() } } }
- 第三步:直接调用即可,纯Swift项目下该扩展默认全局生效,所有继承自UIViewController的子类不需要额外导入文件,在需要弹出提示的位置直接写
self.showToast(message: "你要展示的提示内容")即可调用。
补充说明
- 如果你的项目需要支持Objective-C调用这个扩展方法,可以在
func showToast前面加上@objc标记 - 现有实现用了固定frame计算位置,如果需要适配横竖屏切换,可以把frame的实现替换为AutoLayout约束,避免屏幕旋转后Toast位置偏移
内容的提问来源于stack exchange,提问作者E.Rawrdríguez.Ophanim
相关产品推荐
相关产品推荐

