真ん中にタイトルのあるUIButtonがあります。ボタンの左側と右側に画像(アイコン)を表示したい。左側は簡単で、手動で座標を設定するだけです。しかし、右側では、ディスプレイが回転してボタンが拡大されたときに、画像を「x」軸に沿って移動する必要があります。
これを行う方法 ?
真ん中にタイトルのあるUIButtonがあります。ボタンの左側と右側に画像(アイコン)を表示したい。左側は簡単で、手動で座標を設定するだけです。しかし、右側では、ディスプレイが回転してボタンが拡大されたときに、画像を「x」軸に沿って移動する必要があります。
これを行う方法 ?
button1というUIButtonがあるとすると、次のようなことができます。
imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
imageView1.center = CGPointMake(25, button1.frame.size.height / 2);
imageView1.image = [UIImage imageNamed:@"ThumbsUp.png"];
[button1 addSubview:imageView1];
[imageView1 release];
imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
imageView2.center = CGPointMake(button1.frame.size.width - 25, button1.frame.size.height / 2);
imageView2.image = [UIImage imageNamed:@"ThumbsDown.png"];
[button1 addSubview:imageView2];
[imageView2 release];
ここでは、ボタンに2つの画像ビューを追加し、それらの中心を使用して配置します。imageView1の場合、ボタンの左から25ピクセルに設定します。imageView2の場合、ボタンの幅から25を引きます。
次に、回転コードを設定する必要があります。
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation) interfaceOrientation duration:(NSTimeInterval)duration {
if (interfaceOrientation == UIDeviceOrientationPortrait || interfaceOrientation == UIDeviceOrientationPortraitUpsideDown) {
[button1 setFrame:CGRectMake(10, 100, 300, 50)];
} else {
[button1 setFrame:CGRectMake(40, 50, 400, 50)];
}
imageView2.center = CGPointMake(button1.frame.size.width - 25, button1.frame.size.height / 2);
}
ここでは、縦向きか横向きかに応じてボタンのフレームを変更し、最後にimageView2の中心を設定してさまざまなフレームに合わせて調整します。imageView1は同じままなので、気にする必要はありません。
このReversedUIButtonhttps://gist.github.com/fabnoe/bbf9545769d4a149faaeを使用することもでき ます