我遇到了同样的问题。
我试图解决它并想出了这个解决方案。
我认为这不是一个完美的解决方案,并且可能不适用于每个 iOS 版本。
首先你需要像这样子类化 UISwitch:
@interface UICustomSwitch : UISwitch
@property (assign, nonatomic) CGFloat scale;
@end
@implementation UICustomSwitch
- (void)setFrame:(CGRect)frame {
CGFloat superview_height = self.superview.frame.size.height;
frame.origin.y = (superview_height - frame.size.height * _scale) / 2;
[super setFrame:frame];
}
@end
要做的第二件事是像这样创建和设置您的 UICustomSwitch:
UICustomSwitch* switch = [UICustomSwitch new];
switch.transform = CGAffineTransformMakeScale(0.75, 0.75);
switch.scale = 0.75;
UIBarButtonItem* button = [[UIBarButtonItem alloc] initWithCustomView:switch];
要在 175 和交换机之间创建更大的空间,您可以在 175 和交换机之间添加另一个 UIBarButtonItem。例如。具有特定宽度的固定间隔。
就像我说的,我不认为这是一个完美的解决方案。
在我的测试中,它起作用了。
0yeoj 的另一个解决方案(但稍作调整 -> 始终为每个 navigationBar 高度居中,对于工具栏它是相同的,只需使用 self.navigationController.toolbar.frame.size.height ):
UIView* switch_container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, self.navigationController.navigationBar.frame.size.height)];
UISwitch* switch = [[UISwitch alloc] initWithFrame:switch_container.bounds];
switch.transform = CGAffineTransformMakeScale(0.75, 0.75);
switch.center = CGPointMake(switch_container.bounds.size.width/2, switch_container.bounds.size.height/2);
[switch addTarget:self action:@selector(action:) forControlEvents:UIControlEventValueChanged];
[switch_container addSubview:switch];
UIBarButtonItem* button = [[UIBarButtonItem alloc] initWithCustomView:switch_container];
self.navigationItem.rightBarButtonItem = button;