Ios 通知视图的公共函数
我已经创建了一个自定义NotificationView,我在几乎每个viewController中都使用它,这意味着我在所有viewController中都有下面的函数。有没有办法只把它放在一个里面,这样就不会重复很多次了 变量Ios 通知视图的公共函数,ios,swift,Ios,Swift,我已经创建了一个自定义NotificationView,我在几乎每个viewController中都使用它,这意味着我在所有viewController中都有下面的函数。有没有办法只把它放在一个里面,这样就不会重复很多次了 变量 var notification:SFSwiftNotification? var notificationFrame:CGRect? 功能 func setUpNotification() { //Notification Setup notific
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!)
}
您可以创建一个
UIViewController
,在其中实现func,并从此根控制器继承所有控制器
如果您有UITableViewController
YourViewController : RootVC <UITableViewDataSource, UITableViewDelegate>
YourViewController:RootVC
别忘了编写委托方法,并在视图上添加
UITableView您只需使用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为什么不在AppDelegate中创建它并从所有ViewController调用它?这看起来像什么?当我有一个TableViewController时我会怎么做?UITableViewController继承自UIViewController,只需实现UITableViewDelegate和UITableViewDatasource协议。您只需更改一行代码,就可以得到相同的结果:将您的TableViewController类化:NotificationViewController、UITableViewDelegate、UITableViewDataSource。NotificationViewController中有您的通知。我想我也需要对UITableViewController执行同样的操作。我无法在此处将委托设置为self?由于我无法添加SFSwiftNotificationProtocol
,因此您也可以在此处添加SFSwiftNotificationProtocol。检查更新的代码。UIViewController
不符合sfswifnotificationprotocol
您会收到该错误,因为您声明将在此处实现sfswifnotificationprotocol,因此您必须添加此协议所需的功能。如果这是一条路的话,很难走到球棒的右边。您在连接到SFSwiftNotificationProtocol的ViewController中还使用了哪些功能?