简体   繁体   English

如何使iOS子视图将自身添加到视图

[英]How to make an iOS subview add itself to a view

I've created a "toast" style activity window class that I can add very simply by creating an instance of the class, then initiating it with the nib "toastView.xib" and adding it as a subview to the current view. 我创建了一个“ toast”样式活动窗口类,可以通过创建该类的实例,然后用笔尖“ toastView.xib”将其初始化,然后将其作为子视图添加到当前视图中,来非常简单地添加它。

What I want to do is simplify this so that I only have to initiate the instance. 我想做的就是简化此过程,这样我只需要启动实例即可。 Then, to conserve memory, I'd like it to only add the subview when I pop up the toast. 然后,为了节省内存,我希望它仅在弹出吐司时添加子视图。 Currently, I do this with one of two methods, but for simplicity just assume it is -(void)loadWithLabel:(NSString *)labelString When this happens, I think the current View Controller must pass the toastView the current main view. 当前,我使用两种方法之一进行此操作,但为简单起见,仅假设它是-(void)loadWithLabel:(NSString *)labelString发生这种情况时,我认为当前的View Controller必须将toastView传递给当前的主视图。 Based on this view, I would like the toastView class to add itself as a subview, so I have to do less work to implement this toast window in View Controllers further down the line. 基于此视图,我希望toastView类将自身添加为子视图,因此,我需要做更少的工作才能在视图控制器中进一步实现此Toast窗口。 If you guys have any suggestions that would be most welcome! 如果你们有什么建议,将非常欢迎您! Sorry about the verbosity, its kind of confusing :) 抱歉,冗长,令人困惑:)

Thanks in advance! 提前致谢!

Summary of the desired behavior: 所需行为的摘要:

My current View Controller (call it currentView) allocates and initializes an instance of toastView class (call it 'toast'). 我当前的View Controller(称为currentView)分配并初始化了toastView类的实例(称为“ toast”)。 When the toast is needed, currentView sends something like [toast loadToastInView:self.view]; 当需要吐司时,currentView发送类似[toast loadToastInView:self.view]; after which toast inserts itself into currentView.view at index 0. After a set time (or on method call), toast releases its view from it's superView, currentView until it's called upon again. 之后, toast将自身插入索引为0的currentView.view在设置的时间之后(或在方法调用时), toast从其superView,currentView中释放其视图,直到再次调用它为止。

I would make a singleton and call it Toast. 我会做一个单身人士,叫它吐司。 Then when I needed a toast I would call 然后当我需要敬酒时,我会打电话给

[[Toast sharedInstance] loadToastInView:self.view]; 

and

[[Toast sharedInstance] removeToast]; 

The Toast singleton would have a UIView member called toastView which is added/removed when those are called and which is loaded from xib on init with Toast单例将有一个名为toastView的UIView成员,该成员在调用时会添加/删除,并在初始化时从xib加载,

[[NSBundle mainbundle] loadNibNamed@"toastView" owner:self options:nil]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM