• iOS: 学习笔记, 添加一个带界面约束的控制器


    1. 创建一个空iOS应用程序(Empty Application).

    2. 添加加控制器类. 修改控制器类的viewDidLoad

     1 - (void)viewDidLoad
     2 {
     3     [super viewDidLoad];
     4     //创建标题
     5     UILabel *header = [[UILabel alloc] init];
     6     header.text = @"欢迎来到我的世界!";
     7     header.textAlignment = NSTextAlignmentCenter;
     8     [self.view addSubview: header];
     9     
    10     self.statusLabel = [[UILabel alloc] init];
    11     self.statusLabel.text = @"准备就绪!";
    12     [self.view addSubview: self.statusLabel];
    13     
    14     
    15     //添加自动布局约束
    16     UILabel *statusLabel = self.statusLabel;
    17     [header setTranslatesAutoresizingMaskIntoConstraints: NO];
    18     [statusLabel setTranslatesAutoresizingMaskIntoConstraints: NO];
    19     
    20     NSMutableArray *contraits = [NSMutableArray array];
    21     NSMutableDictionary *metrics = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@5, @"HPadding", @5, @"VPadding", @20, @"TopMargin", nil];
    22     NSDictionary *views = NSDictionaryOfVariableBindings(header, statusLabel);
    23     [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-HPadding-[header]-HPadding-|" options:0 metrics:metrics views:views]];
    24     [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-HPadding-[statusLabel]-HPadding-|" options:0 metrics:metrics views:views]];
    25     [contraits arrayByAddingObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-HPadding-[statusLabel]-HPadding-|" options:0 metrics:metrics views:views]];
    26     [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-TopMargin-[header]-(>=0)-[statusLabel]-VPadding-|" options:0 metrics:metrics views:views]];
    27 
    28     [self.view addConstraints: contraits];
    29     
    30 }

    3. 修改AppDelegate.m文件

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        // Override point for customization after application launch.
        self.window.backgroundColor = [UIColor whiteColor];
        
        //加入控制器
        self.window.rootViewController = [[DemoViewController alloc] initWithNibName:nil bundle:nil];
        
        [self.window makeKeyAndVisible];
        return YES;
    }

    4. 运行程序, 得到如下效果

  • 相关阅读:
    微信小程序上拉分页
    关于检测数据类型,三种方法(typeof,instanceof,Object.prototype.toString.call())优缺点
    如何在Devc++中配置OpenCv
    数据库系统和应用
    这是一篇测试文档
    Pandas 表格合并
    es6一些好用的方法总结
    前端面试题
    超有趣! JS是怎么计算1+2!!!
    彻底理解闭包
  • 原文地址:https://www.cnblogs.com/yaoyu126/p/3764423.html
Copyright © 2020-2023  润新知