iOS - 在 UINavigationBar 中调整 UISwitch 的大小

标签 ios objective-c ios8 uinavigationbar uiswitch

我正在尝试在我的 UINavigationBar 中使用 UISwitch。我想要一个比默认开关更小的开关,所以我使用 anonymousSwitch.transform = CGAffineTransformMakeScale(0.55, 0.55); 缩小尺寸 当我这样做时,开关缩小了,但我不知道如何缩小将它与我的 UINavigationBar 中的其他元素垂直对齐。 这是目前的样子: enter image description here

理想情况下,UISwitch 与 175 UILabel 的间距与 X UIButton 与 175 的间距一样UILabelUISwitch 将与 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/

相关文章:

ios - 异步声音

ios - 自定义键盘出现约 5 秒延迟

objective-c - Ho 在混合应用程序(主要语言 ObjC)中从 Swift 获取对 appdelegate 的引用以避免引用循环

iphone - 在您的 App Swift 代码上启动 Youtube channel

objective-c - 带有 iPhone5(8.0) 模拟器的 xcode 6 - 当我运行项目时显示 Clang 错误

ios - 检查BOOL状态是否足够?还是应该检查错误?

ios - AFNetworking 2.0//如何读取响应头

iphone - 使 NSOperation 同步

ios - 在 iOS 上使用 GCM 获取 'unknown token'

objective-c - 我怎样才能让 NSLog 更好地描述数组的内容?