左右带有图片的UIButton

5

我有一个标题位于中间的UIButton。我想在按钮的左右两侧显示图像(图标)。在左侧,这很容易,我只需手动设置坐标即可。但在右侧,当显示旋转并且按钮被放大时,我需要将图像沿“x”轴移动。

如何实现?


为什么不尝试将两个UIImageView作为按钮的子视图添加,并为它们设置框架? - RomanHouse
我正在使用UIImageViews...但如何为右侧的设置框架... - Martin Perry
2个回答

9
假设你有一个名为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];

这里我们向按钮添加了两个图像视图,并使用它们的中心来定位它们。对于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保持不变,因此我们不必担心它。


您在好的回答后面添加无关的链接和签名,这样会破坏它们的质量。请停止这样做。 - jrturton
当文本太长以至于无法在两侧留出足够的空间时会发生什么? - geekay
首先使用Stephen Poletto在这里给出的答案计算按钮标题的宽度。然后,加上两个UIImages的size.width和您所需的任何额外填充。 - Carl Smith

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接