iOS学习用代码写界面,不用ib

本文介绍如何使用纯代码方式在iOS应用中构建基本的用户界面,包括设置背景颜色、添加标签和按钮,并实现按钮点击事件。

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

刚刚开始学习iphone的东西,boss说要用纯代码写界面,那个纠结!

平台:xcode4.1

工程:iphone  viewbased

在loadview中写

- (void) loadView{
    [super loadView];
    UIView *contentView = [[UIView alloc]initWithFrame: [[UIScreen mainScreen] applicationFrame]];
    contentView.backgroundColor = [UIColor lightGrayColor];
    self.view = contentView;
    [contentView release];
    
    //label
    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0.0, 0.0, 320, 30)];
    label.text = @"PureCode";
    label.center = contentView.center;
    label.backgroundColor = [UIColor lightGrayColor];
    label.textAlignment = UITextAlignmentCenter;
    [self.view addSubview:label];
    [label release];
 
    //button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setFrame:CGRectMake(10.0, 20.0, 77, 37)];
    [button setTitle:@"Button" forState:UIControlStateNormal];
    [button setTitle:@"ok" forState:UIControlStateDisabled];
    [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

}

按钮事件,在viewcontroller.h中:

- (void) buttonPressed:(id)sender;

相应的在.m文件中:

 - (void)buttonPressed:(id)sender{
   UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"ButtonPressed"
                                    message:@"You have pressed the button"
                                    delegate:nil
                                    cancelButtonTitle:@"Yesh"
                                    otherButtonTitles: nil];
    [alert show]; 
} 


上图:




可以增加其它控件:

//image

    UIImage *image = [UIImage imageNamed:@"raw.png"];

    UIImageView  *imageView = [[UIImageView alloc]initWithImage:image];

    [imageView setFrame:CGRectMake(100, 100, 157, 57)];

    [imageView sizeToFit];

    imageView.backgroundColor = [UIColor blueColor];

    [self.view addSubview:imageView];

     

    [imageView release];


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值