How do I create a basic UIButton programmatically?

后端 未结 30 1245
清歌不尽
清歌不尽 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:13

    try this:

    first write this in your .h file of viewcontroller

    UIButton *btn;
    

    Now write this in your .m file of viewcontrollers viewDidLoad.

    btn=[[UIButton alloc]initWithFrame:CGRectMake(50, 20, 30, 30)];
    [btn setBackgroundColor:[UIColor orangeColor]];
    [btn setTitle: @"My Button" forState:UIControlStateNormal];
    [btn setTitleColor: [UIColor blueVolor] forState:UIControlStateNormal];
    [btn.layer setBorderWidth:1.0f];
    [btn.layer setBorderColor:[UIColor BlueVolor].CGColor];
    //adding action programatically
    [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    

    write this outside viewDidLoad method in .m file of your view controller

    - (IBAction)btnClicked:(id)sender
    {
      //Write a code you want to execute on buttons click event
    }
    

提交回复
热议问题