开发时遇到的问题:需要设置导航栏的rightBarButtonItem的大小和背景颜色,常规用法是直接使用UIButton传给initWithCustomView进行使用,但是此时自定义的button的frame是不受控制的,修改frame并不会起作用。
解决方法:用UIView作为CustomView传入,然后修改frame,这时view的大小就可以自定义了。
代码如下:
UIView *containerView = [UIView new];
containerView.frame = CGRectMake(0,0,48,24); // 系统BarButtonItem大小(34, 30)
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = containerView.bounds; //***
button.backgroundColor = [UIColor redColor];
[button setBackgroundImage:[UIImage imageNamed:@"xxx.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(navigationRightItemClicked:) forControlEvents:UIControlEventTouchUpInside];
[containerView addSubview:button]; //***
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:containerView];
UIButton继承自UIControl,UIControl继承自UIView,理论上是可行的,但至于什么原因,暂时未知,欢迎交流。