【问题标题】:UIButton with image on left and right sideUIButton 左右两边都有图片
【发布时间】:2012-09-14 14:35:48
【问题描述】:

我有一个 UIButton,标题在中间。我想在按钮的左侧和右侧显示图像(图标)。在左侧,很简单,我只是手动设置坐标。但在右侧,当显示旋转和按钮放大时,我需要沿“x”轴移动图像。

如何做到这一点?

【问题讨论】:

  • 为什么不尝试添加两个 UIImageViews 作为按钮的子视图并给它们框架?
  • 我正在使用 UIImageViews...但是为正确的设置框架很热...

标签: objective-c uibutton


【解决方案1】:

假设你有一个名为 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 烦恼,因为它保持不变。

【讨论】:

  • 在末尾添加不相关的链接和签名会破坏其他好的答案。请停下来。
  • 当文本太大而不能在两边留下必要的空间时会发生什么?
  • 首先使用 Stephen Poletto 的回答 here 计算按钮标题的宽度。然后,添加两个 UIImage 的 size.widths 以及您需要的任何其他填充。
【解决方案2】:

你也可以使用这个 ReversedUIButton https://gist.github.com/fabnoe/bbf9545769d4a149faae

【讨论】:

    猜你喜欢
    • 2018-01-04
    • 2016-09-26
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多