我的 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/