两个视图多个UIPickerViews单个插座

Arm*_*and 0 iphone objective-c ipad ios

我的应用程序有两个视图,具体取决于它决定加载哪个视图的方向.但IB不允许我将两个PickerView连接到同一个OUTLET,有没有办法在代码中分配连接,这样当我加载视图时,我将连接分配给插座?

或者我应该为每个视图做两倍的事情吗?

或者我应该将两个视图拆分为不同的nib文件

请帮帮我

谢谢

cdu*_*uhn 5

好吧,请记住,IBOutlet只是一个已经以在IB中可见的方式声明的属性.所以第一个问题的答案是肯定的.如有必要,您始终可以在代码中重新分配该属性.

我认为你已经有两个IBOutlets用于你的风景和肖像视图 - 像这样:

@property (nonatomic, retain) IBOutlet UIView *landscapeView;
@property (nonatomic, retain) IBOutlet UIView *portraitView;
Run Code Online (Sandbox Code Playgroud)

听起来你正在选择合适的视图willAnimateRotationToInterfaceOrientation:duration:.

同样,您可以为选择器视图声明两个出口:

@property (nonatomic, retain) IBOutlet UIPickerView *landscapePickerView;
@property (nonatomic, retain) IBOutlet UIPickerView *portraitPickerView;
Run Code Online (Sandbox Code Playgroud)

如果你走这条路,我会声明一个动态属性,它始终返回当前方向的选择器视图.

@property (nonatomic, retain, readonly) UIPickerView *pickerView;
Run Code Online (Sandbox Code Playgroud)

您可以像这样实现它,而不是合成此属性:

- (UIPickerView *) pickerView {
    if (self.landscapeView.superview) {
        return self.landscapePickerView;
    }
    else {
        return self.portraitPickerView;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您有多个或两个子视图,那么使用这样的并行属性会让您的控制器变得混乱.在这种情况下,我会考虑制作一个UIView的自定义子类,称为PickerContainer,它有pickerView和你需要访问的任何其他子视图的插座.然后在IB中,您可以将景观和纵向视图的类更改为PickerContainer,并且可以将每个选取器直接连接到其超级视图.然后在你的控制器中你可以创建一个这样的动态属性:

@property (nonatomic, retain, readonly) PickerContainer *pickerContainer;

- (PickerContainer *)pickerContainer {
    return (PickerContainer *)self.view;
}
Run Code Online (Sandbox Code Playgroud)

之后,您可以通过其容器访问pickerView以获取当前方向,如下所示:

[self.pickerContainer.pickerView reloadAllComponents];
Run Code Online (Sandbox Code Playgroud)

编辑:这是我willAnimateRotationToInterfaceOrientation:duration:在我的一个项目中实现的方式:

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
    if (UIInterfaceOrientationIsPortrait(interfaceOrientation)) {
        if (self.landscapeView.superview) [self.landscapeView removeFromSuperview];
        self.portraitView.center = CGPointMake(self.view.bounds.size.width / 2,
                                               self.view.bounds.size.height / 2);
        [self.view addSubview:self.portraitView];
    }
    else {
        if (self.portraitView.superview) [self.portraitView removeFromSuperview];
        self.landscapeView.center = CGPointMake(self.view.bounds.size.width / 2,
                                                self.view.bounds.size.height / 2);
        [self.view addSubview:self.landscapeView];
    }
}
Run Code Online (Sandbox Code Playgroud)

我的横向和纵向视图在IB中没有支柱或弹簧配置,这意味着所有边距都是灵活的,但宽度和高度不是.