gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:37:18 25 4
gpt4 key购买 nike

我创建了一个自定义的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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com