1

iPhone アプリを作成していますが、可変 (1 から 3) のボタンを画面の中央に配置する必要があります。各ボタンの間に 20.0f のマージンを持たせ、等間隔にしないでください。私が話していることを示すために、下にきれいな写真を作りました。

私はこれを機能させるのに最も苦労しています。

注意事項:

int btnWidth = 50;
int margin = 20;

画面サイズの定数kScreenWidthと設定があります。kScreenHeight

ループ内で通常のようにボタンを作成していますが、各ボタンの x 位置の計算がわかりません。

for (UIButton *btn in _someArray) {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    int x = ??????????;
    button.frame = CGRectMake( x, (kScreenHeight * 0.75f), 50.0, 30.0);
    [self.controller.currentView addSubview:button];
}

これについての助けをいただければ幸いです。また、よろしくお願いします。

ここに画像の説明を入力

4

1 に答える 1

1

中央に 3 つのボタンが必要だとします。次に、3 つのボタンのそれぞれの x 座標を取得するプロセスを次に示します。

//Define these globally somewhere
CGSize buttonSize = CGSizeMake(50,50);
int numOfButtons = 3; //num of buttons horizontally in one line. this will be 2 for 2nd and 1 for the third line as per your reference screen.
CGFloat maxSeparationBwButtons = 20.0f; //your horizontal margin b/w buttons
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;

CGFloat totalLengthWithOffsets = buttonSize.width*(CGFloat)numOfButtons+(maxSeparationBwButtons)*((CGFloat)(numOfButtons+1));
CGFloat originatingX = (screenWidth - totalLengthWithOffsets)/2.0f;
//global definition ends...

//Now you can use this method to get the desired button's x coordinate
//Note : in 3 buttons the 1st button starts at position 0 and the last at 2 (aka n-1)
-(CGFloat)getXForButtonAtPosition:(int)position
{
  return (originatingX + maxSeparationBwButtons + (buttonSize.width+maxSeparationBwButtons)*(CGFloat)position);
}

上記で、numOfButtons、buttonSize、および maxSeparationBwButtons の値を目的の値に変更できます。

于 2013-08-29T13:10:59.197 に答える