我必须根据设备方向为 UIView 设置一些自定义大小参数。我加载没有自己的视图控制器的 UIView,如下所示:
在 main.h
@property (nonatomic, retain) IBOutlet UIView *socialActionView;
在 main.m
@synthesize socialActionView;
. . .
socialActionView = [[[NSBundle mainBundle] loadNibNamed:@"SocialActionViewController" owner:self options:nil] objectAtIndex:0];
[self.view addSubview:socialActionView];
如果不再需要,我将其从超级视图中删除
[self.socialActionView removeFromSuperview];
NSLog(@"%@",self.socialActionView.superview);
删除后日志显示 (null)
我喜欢这样的尺寸调整
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
if ((self.interfaceOrientation == UIDeviceOrientationPortrait) || (self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown)){
if (self.socialActionView != NULL) {
[self.socialActionView setBounds:CGRectMake(0, 0, 320, 480)];
[self.socialActionView setCenter:CGPointMake(160, 240)];
[self.scroll1 setContentSize:CGSizeMake(320, 600)];
[self.scroll1 setBounds:CGRectMake(0, 0, 320, 428)];
[self.scroll1 setCenter:CGPointMake(160, 266)];
}
} else if((self.interfaceOrientation == UIDeviceOrientationLandscapeLeft) || (self.interfaceOrientation == UIDeviceOrientationLandscapeRight)){
if (self.socialActionView != NULL) {
[self.socialActionView setBounds:CGRectMake(0, 0, 480, 320)];
[self.socialActionView setCenter:CGPointMake(240, 160)];
[self.scroll1 setContentSize:CGSizeMake(480, 600)];
[self.scroll1 setBounds:CGRectMake(0, 0, 480, 268)];
[self.scroll1 setCenter:CGPointMake(240, 186)];
}
}
}
到目前为止工作正常,直到我不从我的主视图中删除子视图(socialAcitonView)。导致之后 self.socialActionView 不再可访问。我在stackoverflow上看到了很多例子,比如
-(IBAction)showPopup:(id)sender {
if(![[self myView] isDescendantOfView:[self view]]) {
[self.view addSubview:[self myView]];
} else {
[[self myView] removeFromSuperview];
}
或者
-(IBAction)showPopup:(id)sender
{
if (!myView.superview)
[self.view addSubview:myView];
else
[myView removeFromSuperview];
}
或者
if (!([rootView subviews] containsObject:[self popoverView])) {
[rootView addSubview:[self popoverView]];
} else {
[[self popoverView] removeFromSuperview];
}
或者
-(IBAction)showPopup:(id)sender {
if([[self myView] superview] == self.view) {
[[self myView] removeFromSuperview];
} else {
[self.view addSubview:[self myView]];
}
}
但它们都不起作用。调试器总是抛出异常导致错误访问。什么(从我的角度来看)意味着该对象不再存在。但是在我从超级视图中删除它并说(null)之后,记录器如何访问它?
我知道最好给视图一个专用的视图控制器并将 didRotateFromInterfaceOrientation 放在那里,这样我就不必检查 socialActionView 是否在那里。无论如何,我想问一下是否有办法检查 UIView 是否为(null)。在我将所有代码更改为视图/视图控制器对之前。
任何提示表示赞赏!