纯代码创建UI界面入门(二)

上文中是在没有storyboard下创建UI,但是那样的方法既繁琐,又不符合MVC设计模式。

所以本文通过IB初始化界面,然后通过代码动态添加UILabel和删除UILabel


#import "ViewController.h"

@interface ViewController ()

@property (strong, nonatomic) NSMutableArray *labels;

@end

@implementation ViewController {
    NSInteger _nextY;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.view setBackgroundColor:[UIColor grayColor]];
    
    //初始化labels数组
    self.labels = [NSMutableArray array];
    
    //获取主视图的宽度
    CGRect rect = [self.view bounds];
    CGFloat width = rect.size.width;
    
    //添加按钮设置在视图宽度1/3处
    UIButton *addButton = [[UIButton alloc] initWithFrame:
                         CGRectMake(width/3 - 20, 50, 40, 20)];
    [addButton setTitle:@"添加" forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:addButton];
    
    //删除按钮设置在视图宽度2/3处
    UIButton *removeButton = [[UIButton alloc] initWithFrame:
                         CGRectMake(2 * width/3 - 20, 50, 40, 20)];
    [removeButton setTitle:@"删除" forState:UIControlStateNormal];
    [removeButton addTarget:self action:@selector(remove:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:removeButton];
    
    _nextY = 100;
}

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

- (IBAction)add:(id)sender {
    CGRect rect = [self.view bounds];
    CGFloat width = rect.size.width;
    //创建一个UILable控件
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(width/2 - 80, _nextY, 160, 30)];
    label.text = [NSString stringWithFormat:@"nextY = %ld", (long)_nextY];
    
    [self.labels addObject:label];
    [self.view addSubview:label];
    
    _nextY += 50; //控制nextY的值加50
}

- (IBAction)remove:(id)sender {
    NSLog(@"remove");
    NSLog(@"%lu",(unsigned long)[self.labels count]);
    if ([self.labels count] > 0) {
        //将最后一个labels删除
        [[self.labels lastObject] removeFromSuperview];
        [self.labels removeLastObject];
        
        _nextY -= 50;
    }
}

@end


参考资料:《疯狂ios讲义》

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值