You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 03:39:02