UIBarButtonItem代码不起作用

时间:2012-10-22 19:23:45

标签: ios uibarbuttonitem

我尝试使用普通的大尺寸图标,根本没有调整大小,并且UIBarButtonItemStyleBordered有效:

UIBarButtonItem *compassButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"compass.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(compassButtonPressed:)];
compassButtonItem.enabled = YES;
self.navigationItem.rightBarButtonItem = compassButtonItem;

UIBarButtonItem initWithImage

然后我尝试使用UIButton和CGRectMake将图像大小调整为20x20,边框不起作用:

UIButton *compassButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
UIImage *compassImage = [UIImage imageNamed:@"compass.png"];
[compassButton addTarget:self action:@selector(compassButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[compassButton setImage:compassImage forState:UIControlStateNormal];
[compassButton setImage:compassImage forState:UIControlStateSelected];
UIBarButtonItem *compassButtonItem = [[UIBarButtonItem alloc] initWithCustomView:compassButton];
compassButtonItem.style = UIBarButtonItemStyleBordered;
compassButtonItem.enabled = YES;
self.navigationItem.rightBarButtonItem = compassButtonItem;

UIButton setImage

如何在调整UIImage大小的情况下使用UIBarButtonItemStyleBordered的任何想法?。

1 个答案:

答案 0 :(得分:4)

怎么样:

UIImage *image = [UIImage imageNamed:@"compass.png"];
CGSize newSize = CGSizeMake(20.0f, 20.0f); 
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIBarButtonItem *compassButtonItem = [[UIBarButtonItem alloc] initWithImage:thumbnail style:UIBarButtonItemStyleBordered target:self action:@selector(refreshSection)];  
self.navigationItem.rightBarButtonItem = compassButtonItem;