ios - 调整 UIBarButtonItem 的 Imageview 的大小,以便按比例缩小图像 (iOS)

标签 ios uiimage uibarbuttonitem uitoolbar

我的 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];

最佳答案

我假设添加自定义 View 与使用 initWithCustomView: 创建栏按钮项目时的效果相同。在那种情况下,文档说,

The bar button item created by this method does not call the action method of its target in response to user interactions. Instead, the bar button item expects the specified custom view to handle any user interactions and provide an appropriate response.

因此,您应该向 ImageView 添加一个点击手势识别器,并为其设置一个操作方法,

- (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");
}

关于ios - 调整 UIBarButtonItem 的 Imageview 的大小,以便按比例缩小图像 (iOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23190643/

相关文章:

iphone - UIToolbar UIBarButtonItem 对齐问题

ios - 在其图像上显示 UIBarButton 标题

ios - XML 到字典的复杂转换 (Swift/iOS)

ios - 如何将 .xib 界面设置为自定义标注 View ?

iphone - 如何正确裁剪在 iPhone 4G 上拍摄的图像(带有 EXIF 旋转数据)?

ios - 如何在不透明的 UIImage 上用另一种颜色替换给定颜色

objective-c - 使用 UIImage 黑白 iOS 屏蔽 UIView

ios - iphone UIBarButtonItem : setBackgroundImage - Stretched

ios - 如何在 UINavigationController 堆栈中使用 didReceiveMemoryWarning

iOS:alpha相关视觉效果