【发布时间】:2023-11-28 11:55:02
【问题描述】:
我在没有初始化的情况下分配了一个视图控制器,但一切正常。视图控制器中的子视图工作正常。
这里是代码。
self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
[self.window makeKeyAndVisible];
self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[ViewController alloc]];
ViewController.m 中的代码
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self test];
}
- (void)test
{
self.view.backgroundColor = [UIColor whiteColor];
CGRect frame = CGRectMake( 50, 100, 200, 200);
UIScrollView *scrollView= [[UIScrollView alloc] initWithFrame:frame];
[self.view addSubview:scrollView];
frame= CGRectMake( 0, 0, 500, 500);
UIImageView *myImageView= [[UIImageView alloc] initWithFrame:frame];
[scrollView addSubview:myImageView];
scrollView.contentSize = CGSizeMake(500,500);
scrollView.backgroundColor = [UIColor blackColor];
myImageView.backgroundColor = [UIColor yellowColor];
scrollView.contentOffset = CGPointMake(0, 0);
}
@end
【问题讨论】:
-
ViewController真的有什么作用吗? -
我把ViewController.m的代码放在问题描述里了。
-
好吧,如果我没记错的话
init主要只是初始化变量。你似乎没有任何全局的,我很确定ViewController扩展了NSObject,所以也许你不需要打电话给init。 -
@Arc676 非常感谢!
-
它的工作原理是运气不好。不要写这样的代码。碰巧 UIViewController 及其祖先没有初始化
init中的任何关键内容。
标签: ios objective-c uiviewcontroller init alloc