我正在尝试在我的 UINavigationBar
中使用 UISwitch
。我想要一个比默认开关更小的开关,所以我使用 anonymousSwitch.transform = CGAffineTransformMakeScale(0.55, 0.55);
缩小尺寸 当我这样做时,开关缩小了,但我不知道如何缩小将它与我的 UINavigationBar
中的其他元素垂直对齐。
这是目前的样子:
理想情况下,UISwitch
与 175 UILabel
的间距与 X UIButton
与 175 的间距一样UILabel
,UISwitch
将与 UINavigationBar
中的其余元素在一条直线上。我尝试执行 switch.center = CGPointMake(switch.center.x, shareButton.center.y)
,但这根本不影响 UISwitch
的放置。
有什么方法可以让我按照自己的意愿定位开关吗?
最佳答案
我遇到了同样的问题。
我试图解决它并想出了这个解决方案。
我认为这不是一个完美的解决方案,可能不适用于每个 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;
关于iOS - 在 UINavigationBar 中调整 UISwitch 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29045345/