我已经在这里检查了许多接近的答案,没有人能解决我的愚蠢问题。
我的问题是:我有2个类,即UIViewController classA和UIView classB。
一个按钮(classA)触发到process(classB),然后在屏幕上显示子视图(classA)。
但这是行不通的。
class.m:
@implementation ViewController
...
- (IBAction)trigger:(UIButton *)sender {
[classB makeViewOn];
}
classB .h:
#import <UIKit/UIKit.h>
@interface classB : UIView
+ (void)makeViewOn;
@end
classB .m:
#import "classB.h"
#import "ViewController.h"
@implementation classB
+ (void)makeViewOn
{
ViewController *pointer = [ViewController new];
UIWindow *window = pointer.view.window;
classB *overlayView = [[classB alloc] initWithFrame:window.bounds];
overlayView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5f];
overlayView.userInteractionEnabled = YES;
[pointer.view addSubview:overlayView];
}
@end
如果仅在一个类UIViewController中执行此操作,则它会正常工作;但是,如果我在两个单独的类(UIViewController和UIView)上执行此操作,该如何解决呢?
我在类之间进行交流的基本概念上做错了吗?
非常感谢!
最佳答案
首先,您正在创建一个名为ViewController类的指针的新对象,因此,您的classB对象overlayView不会作为子视图添加到classA而是对象指针。
其次,如果您打印并检查您的window.bounds返回(空)。
在classB中修改您的类方法
+ (void)makeViewOnParentView:(id)sender;
+ (void)makeViewOnParentView:(id)sender
{
ViewController *pointer = (ViewController*)sender;
//UIWindow *window = pointer.view.window;
CGRect rect=pointer.view.frame;
classB *overlayView = [[classB alloc] initWithFrame:CGRectMake(0, 0,rect.size.width, rect.size.height)];
overlayView.backgroundColor = [[UIColor greenColor] colorWithAlphaComponent:0.5f];
overlayView.userInteractionEnabled = YES;
[pointer.view addSubview:overlayView];
}
并在您的classA中调用方法
[classB makeViewOnParentView:self];
希望这对您有用...