How do I create a basic UIButton programmatically?

后端 未结 30 1221
清歌不尽
清歌不尽 2020-11-22 14:41

How can I create a basic UIButton programmatically? For example in my view controller, when executing the viewDidLoad method, three UIButton<

30条回答
  •  不知归路
    2020-11-22 15:19

    Come on, it's 2014! Why isn't code block evaluation assignment being used yet, as trends show it's the future!

    UIButton* button = ({
        //initialize button with frame
        UIButton* button = [[UIButton alloc] initWithFrame:({
            CGRect frame = CGRectMake(10.0, 10.0, 200.0, 75.0);
            frame;
        })];
        //set button background color
        [button setBackgroundColor:({
            UIColor* color = [UIColor colorWithRed:1.0 green:1.0 blue:0.0 alpha:1.0];
            color;
        })];
        //set button title for state
        [button setTitle:({
            NSString* string = [NSString stringWithFormat:@"title words"];
            string;
        }) forState:({
            UIControlState state = UIControlStateNormal;
            state;
        })];
        //set selector
        [button addTarget:self action:({
            SEL select = @selector(method:);
            select;
        }) forControlEvents:({
            UIControlEvents event = UIControlEventTouchUpInside;
            event;
        })];
        //return button
        button;
    });
    [self.view addSubview:button];
    

    whoa!

    whoa!

    Or the exact results can be accomplished as such:

    UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(10.0, 10.0, 200.0, 75.0)];
    [button setBackgroundColor:[UIColor colorWithRed:1.0 green:1.0 blue:0.0 alpha:1.0]];
    [button setTitle:@"title words" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(method:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    

提交回复
热议问题