iOS编程(双语版) - 视图 - 手工代码(不使用向导)创建视图

如何创建一个空的项目,最早的时候XCode的项目想到中,还有Empty Application template这个选项,后来Apple把它

给去掉了。

我们创建一个单视图项目。

1) 删除main.storyboard

2) 删除ViewController相关文件

3) 删除AppDelegate的所有内容

给你的AppDelegate加入如下内容:

(Objective-C代码)

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    // 指定窗口的根视图控制器
    self.window.rootViewController = [UIViewController new];
    UIView* mainview = self.window.rootViewController.view;
    
    // 将自定义视图增加为窗口根视图控制器视图的子视图
    UIView* v = [[UIView alloc] initWithFrame:CGRectMake(100,100,50,50)];
    v.backgroundColor = [UIColor redColor]; // small red square
    [mainview addSubview: v]; // add it to the main view
    
    // 使窗口可见
    self.window.backgroundColor = [UIColor whiteColor];    
    [self.window makeKeyAndVisible];
    
    return YES;
}

(Swift代码-iOS9)

func application(application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    self.window = UIWindow()
    
    // 指定窗口的根视图控制器
    self.window!.rootViewController = UIViewController()    
    let mainview = self.window!.rootViewController!.view
    
    // 将自定义视图增加为窗口根视图控制器视图的子视图
    let v = UIView(frame:CGRectMake(100,100,50,50))
    v.backgroundColor = UIColor.redColor() // small red square
    mainview.addSubview(v) // add it to main view
    
    // 使窗口可见
    self.window!.backgroundColor = UIColor.whiteColor()
    self.window!.makeKeyAndVisible()
    
    return true
}

运行结果:

在白色背景下看到一个红色的矩形

如何删除所有子视图?

Apple很奇怪地没有提供这一API,所以我们只好自己干啦。

(Objective-C代码)

for (UIView* v in view.subviews)
    [v removeFromSuperview];

// 或者可以这样
[view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

(Swift代码-iOS9)

myView.subviews.forEach {$0.removeFromSuperview()}

转载于:https://www.cnblogs.com/davidgu/p/5704104.html

猜你喜欢

转载自blog.csdn.net/weixin_33713503/article/details/93803078