【问题标题】:Resizing UIBarButtonItem's Imageview so that the Image is Scaled Down (iOS)调整 UIBarButtonItem 的 Imageview 的大小,以便缩小图像 (iOS)
【发布时间】:2014-04-21 04:06:08
【问题描述】:

我的 UIToolbar 中有一个按钮,我已为其分配了一个图像,但我希望图像自动按比例缩小(在应用程序外部调整图像大小会降低其质量)。

我尝试了解决方案here,它创建了一个自定义 imageView,然后将其分配给按钮。但是,图像似乎没有出现。这是我的代码:

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"info.png"]];
    imageView.frame = CGRectMake(0, 0, 35, 35);
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.userInteractionEnabled = YES;
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:imageView];
    self.tutorial_lbl = barButtonItem;

请注意,如果我注释掉最后两行并改用下面的行,图像确实会出现,但随后会失去按钮的操作。

[self.tutorial_lbl setCustomView:imageView];

【问题讨论】:

    标签: ios uiimage uibarbuttonitem uitoolbar


    【解决方案1】:

    我假设添加自定义视图与使用 initWithCustomView: 创建条形按钮项时的作用相同。在这种情况下,文档说,

    此方法创建的条形按钮项不调用动作 其目标响应用户交互的方法。相反, 条形按钮项期望指定的自定义视图来处理任何用户 互动并提供适当的回应。

    所以,你应该在图像视图中添加一个点击手势识别器,并为其设置一个动作方法,

    - (void)viewDidLoad {
        [super viewDidLoad];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];
        imageView.image = [UIImage imageNamed:@"info.png"];
        UITapGestureRecognizer *tapper = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(barButtonTapped:)];
        [imageView addGestureRecognizer:tapper];
        imageView.userInteractionEnabled = YES;
        [self.tutorial_lbl setCustomView:imageView];
    }
    
    -(void)barButtonTapped:(UITapGestureRecognizer *) sender {
        NSLog(@"Tapped");
    }
    

    【讨论】:

    • 谢谢,这太棒了!一个问题 - 是否有任何方法可以使按钮保留其“点击时突出显示”属性。这样做会将按钮变成静态图像(尽管该操作确实有效)。
    • @Kyle,我认为您也必须自己实现。您可以通过在两张不同的图像之间切换来做到这一点,其中一张比另一张更暗。
    • 啊,有道理。我会试试看!
    【解决方案2】:

    您可以尝试做的一件事是设置图像插图。 UIButtonUIBarButtonItem 都支持图像插入。您无需为此添加UIImageView。只需在按钮上设置图像,然后设置图像插图。

    myButton.imageEdgeInsets = UIEdgeInsetsMake(TOP, LEFT, BOTTOM, RIGHT);//UIButton
    
    myBarButtonItem.imageInsets = UIEdgeInsetsMake(TOP, LEFT, BOTTOM, RIGHT);//UIBarButtonItem
    

    这会调整按钮上的图像大小。正值会缩小图片,负值会放大图片。

    【讨论】:

    • 我试过这个,但无法让左右值起作用。虽然我可以调整顶部和底部值的大小,但无论我使用什么值,左右都会保持拉伸。
    • 没有。当我使用它时,它似乎适用于 iOS 6.x,但 @rdelmar 的解决方案似乎最优雅(和实用)。
    【解决方案3】:

    我能够通过执行以下操作来实现这一点:

    let originalImage = UIImage(named: "SearchIcon")
    let scaledIcon = UIImage(CGImage: originalImage!.CGImage!, scale: 5, orientation: originalImage!.imageOrientation)
    let rightButton = UIBarButtonItem(image: scaledIcon, style: .Plain, target: self, action: #selector(MeViewController.showSearchUsers))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-16
      相关资源
      最近更新 更多