简体   繁体   中英

How to add a button to a UIScrollView as a subView from outside the same method?

So I am trying to get a simple UIScrollView working with a bunch of buttons. I was successfully able to accomplish this task with the following code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [_scroller setScrollEnabled:YES];
    [_scroller setContentSize:CGSizeMake(320, 1487)];

    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -500, 320, 2800)];
    [imgView setBackgroundColor:[UIColor blackColor]];
    [_scroller addSubview:imgView];


    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn1 setTitle:@"Cool title" forState:UIControlStateNormal];
    [btn1 setFrame:CGRectMake(7, 7, 150, 160)];
    [btn1 setImage:[UIImage imageNamed:@"small.png"] forState:UIControlStateNormal];
    [btn1 addTarget:self action:@selector(btn1_m) forControlEvents:UIControlEventTouchUpInside];
    [_scroller addSubview:btn1];

However, what if I to add buttons through interface builder instead of programmatically adding them? Whenever I do this, the scroller no longer scrolls!

For example, if I use the following code after control-dragging a button:

- (IBAction)theButton:(UIButton *)sender {
    [_scroller addSubview:sender];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [_scroller setScrollEnabled:YES];
    [_scroller setContentSize:CGSizeMake(320, 1487)];
}

...The scroll doesn't work, I see the button but nothing scrolls anymore. Basically, I just want to use interface builder to add buttons to my app and have them scroll too, but can't seem to get this to work!

When you create your UI programmatically, the subviews of your scrollview are like this:

ImageView
Button
Button
...

When you use IB to add your buttons, you end up with this:

Button
Button
...
ImageView

Place a breakpoint after your image view is added to the scroll view. In the LLDB console type:

(lldb) po _scroller.subviews

I suspect you will see your image view at the bottom of the list. It is covering your buttons, but it is scrolling, it just doesn't look like it as it is a large black image view.

Send your image view to the back of the subview list:

[_scroller sendSubviewToBack:imgView];

Then you will see your buttons again. Also, after you have done this, confirm your scrollview content size in lldb:

(lldb) p _scroller.contentSize

If it all looks correct, it should be scrolling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM