ios - 通知 View 的公共(public)函数

标签 ios swift

我创建了一个自定义的NotificationView,我几乎在每个 View Controller 中都使用它,这意味着我在所有 View Controller 中都有以下功能。有没有办法只包含一个,这样就不会重复很多次?

变量

var notification:SFSwiftNotification?
var notificationFrame:CGRect?

功能

func setUpNotification() {
    //Notification Setup
    notificationFrame = CGRectMake(0, 0, CGRectGetMaxX(self.view.frame), 64)
    notification = SFSwiftNotification(frame: notificationFrame!,
        title: nil,
        image: "Error",
        animationType: AnimationType.AnimationTypeCollision,
        direction: Direction.TopToBottom, delegate: self)
    notification!.backgroundColor = UIColor.whiteColor()
    notification!.label.textColor = UIColor.blackColor().colorWithAlphaComponent(0.6)
    UIApplication.sharedApplication().keyWindow!.addSubview(notification!)
}

最佳答案

您可以只使用extension,顾名思义,它是对象的扩展。因此,如果您为 UIViewController 创建扩展,那么从 UIViewController 继承的所有对象都将能够使用此扩展。因此,您创建一个如下所示的 .swift 文件:

var notification:SFSwiftNotification?
var notificationFrame:CGRect?

extension UIViewController: SFSwiftNotificationProtocol  {


        func setUpNotification() {
        //Notification Setup
        notificationFrame = CGRectMake(0, 0, CGRectGetMaxX(self.view.frame), 64)
        notification = SFSwiftNotification(frame: notificationFrame!,
            title: nil,
            image: "Error",
            animationType: AnimationType.AnimationTypeCollision,
            direction: Direction.TopToBottom, delegate: self)
        notification!.backgroundColor = UIColor.whiteColor()
        notification!.label.textColor = UIColor.blackColor().colorWithAlphaComponent(0.6)
        UIApplication.sharedApplication().keyWindow!.addSubview(notification!)
        }
}

在所有 ViewController 中,您现在只需执行:self.setUpNotification()

编辑

扩展 UIViewController: SFSwiftNotificationProtocol 中添加了 SFSwiftNotificationProtocol

关于ios - 通知 View 的公共(public)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35935335/

相关文章:

Swift SceneKit - 如何对齐节点的 y 轴以与某些 SCNVector3 重合?

ios - 无法分配给属性 : 'b0' is a get-only property

ios - 有没有办法在不使用 Apple 开发人员门户的情况下将设备添加到配置文件?

ios - PerformSegueWithIdentifier 未呈现所需的 View

ios - 如何在编辑表格 View 单元格中的文本字段时重新加载所有表格 View 单元格 - iOS Swift

ios - 具有超越标签栏的透明背景的 Swift 模态视图 Controller

swift - 应用程序 iCloud 文档目录在安装应用程序后无法加载文件

ios - 在 iOS Swift 中检测设备上正在播放哪个音轨

ios - 在 Apple Watch 的 ReactJS Native 上,如何设置要为 WatchKit 和 Glances 显示的静态图像?

ios - 我应该将 'Strip Debug Symbols During Copy' 和 'Strip Linked Produts' 与 Google Analytics 一起使用吗?