我想添加一个将持续整个应用程序的视图?

时间:2014-03-18 10:37:22

标签: ios iphone uiviewcontroller

我想添加一个将持续整个应用程序的视图? 我怎样才能做到这一点?

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0, 430, 320, 50)];
    myView.backgroundColor = [[UIColor redColor]colorWithAlphaComponent:0.5];
    [self.window addSubview:myView];

这不起作用。 提前谢谢......

1 个答案:

答案 0 :(得分:1)

实现这一目标有几种方法。目前尚不清楚是否希望每个视图控制器中都有视图,或者您希望每个视图控制器中都有相同的实例

由于我没有看到任何理由有一个共享实例(基于您的描述),我的方法是子类UIViewController,让我们称之为SOMyViewController,然后继承所有视图控制器在您的应用中SOMyViewController

然后,我将覆盖SOMyViewController的'viewDidLoad'方法,如下所示:

- (void) viewDidLoad {
    [super viewDidLoad];

    if ([self addMyCustomView]) {
        UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0, 430, 320, 50)];
        myView.backgroundColor = [[UIColor redColor]colorWithAlphaComponent:0.5];
        [self.window addSubview:myView];    
    }
}

/**
 Override this in all your subclasses to decide whether to display the custom view or not
 */
- (BOOL) addMyCustomView {
    return YES;
}

如果您希望在视图控制器之间共享相同的实例,我将按如下方式更改上述代码:

static UIView *mySharedView;

+ (void) initialize {
    mySharedView = [[UIView alloc]initWithFrame:CGRectMake(0, 430, 320, 50)];
    mySharedView.backgroundColor = [[UIColor redColor]colorWithAlphaComponent:0.5];
}

- (void) viewDidLoad {
    [super viewDidLoad];

    if ([self addMyCustomView]) {
        [self.window addSubview:mySharedView];    
    }
}

/**
 Override this in all your subclasses to decide whether to display the custom view or not
 */
- (BOOL) addMyCustomView {
    return YES;
}