for循环快速创建按钮

161 阅读1分钟
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建上下左右四个按钮
    for (NSInteger i = 0; i < 4; i++) {
        UIView *baseView = [[UIView alloc] init];
        baseView.backgroundColor = [UIColor grayColor];
        CGFloat size = self.view.frame.size.width / 4;
        baseView.frame = CGRectMake(size * i, 200 - size, size, size);
        [self.view addSubview:baseView];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(10, 10, size - 20, size - 20);
        [button setBackgroundColor:[UIColor purpleColor]];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont fontWithName:@"Futura-Medium" size:18];
        button.clipsToBounds = YES;
        button.layer.cornerRadius = button.frame.size.width / 2;
        button.tag = i;
        [button addTarget:self action:@selector(buttonTap:) forControlEvents:UIControlEventTouchUpInside];
        [baseView addSubview:button];
        
        if (i == 0) { [button setTitle:@"Up" forState:UIControlStateNormal]; }
        if (i == 1) { [button setTitle:@"Down" forState:UIControlStateNormal]; }
        if (i == 2) { [button setTitle:@"Left" forState:UIControlStateNormal]; }
        if (i == 3) { [button setTitle:@"Right" forState:UIControlStateNormal]; }
    }
}

- (void)buttonTap:(UIButton *)sender {
    NSLog(@"%@",sender.titleLabel.text);
}

@end