开发时遇到的问题:需要设置导航栏的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,理论上是可行的,但至于什么原因,暂时未知,欢迎交流。
iOS导航栏按钮大小及背景颜色设置问题解决
开发中设置导航栏rightBarButtonItem的大小和背景颜色时,用UIButton传给initWithCustomView,其frame不受控制。解决办法是用UIView作为CustomView传入,可自定义view大小,虽理论上UIButton可行,但原因未知,欢迎交流。
1万+

被折叠的 条评论
为什么被折叠?



