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

本文介绍如何从零开始创建一个简单的iOS应用,包括创建空项目、添加并自定义控制器类、实现自动布局约束以及设置AppDelegate启动流程等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    //创建标题
    UILabel *header = [[UILabel alloc] init];
    header.text = @"欢迎来到我的世界!";
    header.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview: header];
    
    self.statusLabel = [[UILabel alloc] init];
    self.statusLabel.text = @"准备就绪!";
    [self.view addSubview: self.statusLabel];
    
    
    //添加自动布局约束
    UILabel *statusLabel = self.statusLabel;
    [header setTranslatesAutoresizingMaskIntoConstraints: NO];
    [statusLabel setTranslatesAutoresizingMaskIntoConstraints: NO];
    
    NSMutableArray *contraits = [NSMutableArray array];
    NSMutableDictionary *metrics = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@5, @"HPadding", @5, @"VPadding", @20, @"TopMargin", nil];
    NSDictionary *views = NSDictionaryOfVariableBindings(header, statusLabel);
    [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-HPadding-[header]-HPadding-|" options:0 metrics:metrics views:views]];
    [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-HPadding-[statusLabel]-HPadding-|" options:0 metrics:metrics views:views]];
    [contraits arrayByAddingObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-HPadding-[statusLabel]-HPadding-|" options:0 metrics:metrics views:views]];
    [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-TopMargin-[header]-(>=0)-[statusLabel]-VPadding-|" options:0 metrics:metrics views:views]];

    [self.view addConstraints: contraits];
    
}

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. 运行程序, 得到如下效果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值