Search code examples
iphoneiosobjective-cuiscrollviewaddsubview

How to add a button in UIScrollView with addSubview?


I am new to iOS development and I have a problem with UIScrollView. First of all, I've created a Scroll View in a storyboard and added

@property (retain, nonatomic) IBOutlet UIScrollView *mainScroll;

in view controller handler

In the viewDidLoad method I have the following code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.mainScroll.contentSize = CGSizeMake(100.0,100.0); // Have to set a size here related to your content.
    // You should set these.
    self.mainScroll.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    self.mainScroll.minimumZoomScale = .5;  // You will have to set some values for these
    self.mainScroll.maximumZoomScale = 2.0;
    self.mainScroll.zoomScale = 1;

    UIButton* b = [[UIButton alloc] init];
    [b setBounds:CGRectMake(.0f,0.f,100.0,100.0)];
    [self.mainScroll addSubview:b];
}

But the button does not appear in the simulator. However if I add a button on storyboard in the IB, the button appears and I can scroll the view.

How can I add the button in code?


Solution

  • Try this code

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:@"Show View" forState:UIControlStateNormal];
    button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
    [self.mainScroll addSubview:button];