How to add a UIButton at runtime

前端 未结 5 1476
予麋鹿
予麋鹿 2020-12-31 05:23

I am trying to add a UIButton at runtime however it is not visible. What am I doing wrong?

- (id)initWithFrame:(CGRect)frame {
    if (self = [s         


        
相关标签:
5条回答
  • 2020-12-31 05:26

    You don't need to retain the UIButton because it is retained by [self.view addSubview:btn];

    0 讨论(0)
  • 2020-12-31 05:29

    First check whether your code is executing the initwithFrame method. Because if you are loading the view from nib i.e using

    NSArray *xibviews = [[NSBundle mainBundle] loadNibNamed: @"MySubview" owner: mySubview options: NULL];
    MySubview *msView = [xibviews objectAtIndex: 0];
    [self.view addSubview:msView]; 
    

    Then the initWithFrame part will not be executing.So please check once.

    0 讨论(0)
  • 2020-12-31 05:43

    First, make sure the initWithFrame: method is being called. If your view is in a Nib, initWithCoder: is being called instead.

    Second, is the button the only subview (from your code it looks like it is, but you never know). The button could be hidden behind another subview. Call bringSubviewToFront: if you need to.

    Finally, is the view itself visible? Is it big enough to show the button? Given your example, if the view is less than 100 pixels wide, the button won't show because it will get clipped by the view's bounds.

    0 讨论(0)
  • 2020-12-31 05:43

    if it still doesn't work, try removing the : at the end of the selector name: @selector(buttonClick)

    0 讨论(0)
  • 2020-12-31 05:48

    You must release btn and remove ":" in buttonClick:

    UIButton *btn= [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
    btn.frame = CGRectMake(0, 0, 100, 25);
    btn.backgroundColor = [UIColor clearColor];
    [btn setTitle:@"Play" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn]; 
    [btn release];
    
    0 讨论(0)
提交回复
热议问题