使用代码创建UI界面

本文介绍如何在Xcode 6.1中,针对Single View Application不使用Main.storyboard,而是通过Objective-C代码实现UI界面的创建。教程参照《疯狂iOS讲义》,主要修改ViewController.m文件。

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

其实也不能算原创哈,照着《疯狂ios讲义》来的。

我的Xcode更新到了6.1,新建工程ios里面已经没有Empty Application了,很多书却都是从这里开始的。这个例子是建立了Single View Application,但是不修改默认的Main.storyboard设计文件,直接在程序代码中创建整个UI界面,程序只使用该界面文件中的UIView作为容器。以下是修改ViewController.m文件,整个工程只需要修改这个文件。

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong) NSMutableArray* labels;

@end

@implementation ViewController

int nextY = 80;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor grayColor];
    self.labels = [NSMutableArray array];
    
    UIButton* addButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    addButton.frame = CGRectMake(30, 30, 60, 40);
    [addButton setTitle:@"添加" forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton* removebutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    removebutton.frame = CGRectMake(230, 30, 60, 40);
    [removebutton setTitle:@"删除" forState:UIControlStateNormal];
    [removebutton addTarget:self action:@selector(remove:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:addButton];
    [self.view addSubview:removebutton];
}

- (void)add:(id)sender{
    UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(80, nextY, 160, 30)];
    label.text = @"亚特兰蒂斯";
    label.textColor = [UIColor blueColor];
    [self.labels addObject:label];
    [self.view addSubview:label];
    nextY += 50;
}

- (void)remove:(id)sender{
    if ([self.labels count] > 0) {
        [[self.labels lastObject] removeFromSuperview];
        [self.labels removeLastObject];
        nextY -= 50;
    }
}

/*
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
*/
@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值