简体   繁体   中英

iOS - how to add one UIButton with respect to another?

I am an iOS newbie, so please bear with me. I have a blank page with a button centered in it. I want to add another button to the view, just below the centered button. How would I do that? I have added the first button like this -

float x=60, y=200, dy=50;
CGRect frame = CGRectMake(x, y, 200, dy);
UIButton *inboxButton = [[[UIButton alloc] initWithFrame:frame]autorelease];
inboxButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
inboxButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

....

[theView addSubview:inboxButton];

Just calculate the second frame based on the first

CGRect secondFrame = CGRectMake(CGRectGetMinX(frame),
    CGRectGetMaxY(frame) + 8.0, // some y padding
    CGRectGetWidth(frame),
    CGRectGetHeight(frame));

You are not saying if you need that second one centered by itself - I am assuming that you just want it below, left-aligned with the first one:

UIButton *outboxButton = [[[UIButton alloc] initWithFrame:CGRectMake(frame.x, 
                                                                     frame.y + dy + 10.0f, 
                                                                     frame.width,
                                                                     frame.height)] autorelease];
[theView addSubview:outboxButton];

What I am doing here is simply reusing the horizontal coordinate from the first button. For the vertical coordinate, I am using the original coordinate and add the height and an offset (10.0f) to it. Both, the width and the height are taken from the first button, assuming that they should match in size.

As you will see, there is no way to have this calculation done implicitly, which I assume you actually wanted to find out - that is, by simply supplying some ordering arguments.

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