UIBarButtonItem 代码不起作用
Posted
技术标签:
【中文标题】UIBarButtonItem 代码不起作用【英文标题】:UIBarButtonItem code not working 【发布时间】:2012-10-22 19:23:45 【问题描述】:我尝试使用正常的大尺寸图标,根本没有调整大小,并且 UIBarButtonItemStyleBordered 有效:
UIBarButtonItem *compassButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"compass.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(compassButtonPressed:)];
compassButtonItem.enabled = YES;
self.navigationItem.rightBarButtonItem = compassButtonItem;
然后我尝试使用 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;
任何想法如何使用 UIBarButtonItemStyleBordered 和 UIImage 调整大小?
【问题讨论】:
你没有使用 UIBarButtonItem 作为你使用 UIButton 的指南针。 【参考方案1】:怎么样:
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;
【讨论】:
以上是关于UIBarButtonItem 代码不起作用的主要内容,如果未能解决你的问题,请参考以下文章
UIBarButtonItem 外观代理设置字体属性在 iOS 11 中不起作用
通过操作将 UIBarButtonItem 设置为 backBarButtonItem,不起作用
设置 UIBarButtonItem 动画在 iOS 11 上不起作用