关于设置导航栏BarButtonItem自定义大小的一些疑问和解决方案?

直入正题,当直接使用UIButton传给initWithCustomView的方法来使用,你会发现这个自定义的button的大小是不受控制的,修改它的fram并不会起作用。如何解决这个问题呢?

initWithCustomView传入类型是UIView,所以想到用UIView作为CustomView传入,然后修改frame,这时你会发现,这个view的大小是可以自定义的了。代码如下:(这里直接将button用view包装了一层)

UIView *containerView = [UIView new];
containerView.frame = (CGRect){.size = CGSizeMake(22, 24)}; // 系统BarButtonItem大小(34, 30)

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = containerView.bounds;
button.backgroundColor = [UIColor redColor];
[button setBackgroundImage:[UIImage imageNamed:@"sd_goback"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(navigationLeftItemClicked:) forControlEvents:UIControlEventTouchUpInside];
[containerView addSubview:button];

self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:containerView];

​ 此时你也许会有同样的疑问,为什么UIButton却不能修改大小呢,

​ UIButton继承自UIControl,UIControl继承自UIView,理论上是可行的,但至于什么原因,我也无从知晓... 如果哪个同学能告诉我真正原因,感激不尽!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容