直入正题,当直接使用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,理论上是可行的,但至于什么原因,我也无从知晓... 如果哪个同学能告诉我真正原因,感激不尽!
网友评论