1

编辑:这个问题是由于对接口生成器和类中的属性如何工作缺乏了解。

为什么我不能self.mySubView = anoterhView;像一个可以设置的那样设置self.view = anotherView;

## .h
@interface TestController : UIViewController {
    IBOutlet UIView *mySubView;
}

@property (nonatomic, retain) IBOutlet UIView *mySubView;

##.m

@implements TestController

@synthesize mySubView;

- (void)viewDidLoad { 

    AnotherController *anotherController = [[AnotherController alloc] initWithNibName:nil bundle:nil];
    anotherView = anotherController.view;

    // if i do
    self.view = anotherView;
    // result: replaces whole view with anotherView

    // if i instead do
    self.mySubView = anotherView;
    // result: no change at all

    // or if i instead do:
    [self.mySubView addSubview:anotherView];
    // result: mySubView is now displaying anotherView

}

注意:我正在使用界面生成器。我确定一切都很好,因为 self.view 和 self.mySubView addSubview: 工作正常..

4

4 回答 4

2

要使其自动出现在您的self.view身上,您需要覆盖您的 setter 方法,例如:

- (void)setMySubView:(UIView *)view {
    [mySubView removeFromSuperview];  // removing previous view from self.view
    [mySubView autorelease];
    mySubView = [view retain];
    [self.view addSubview: mySubView]; // adding new view to self.view
}
于 2010-02-04T13:02:13.660 回答
1

mySubview是一个属性,它是对 UIView 对象的引用。因此,当您将UIView对象分配给它时,您只是在更改mySubview所指的内容,而不是在这种情况下,

self.mySubview = anotherView;

mySubview所指的原始 UIView 对象仍然在viewsubviews属性中被引用。没有什么变化。

但是当您将anotherView添加为mySubview的子视图时,anotherView属于视图层次结构并显示在屏幕上。所以这行得通。

view (parent of) mySubview (parent of) anotherView

但是,当您将anotherView直接分配给视图时,您不仅会更改视图所指的 UIView 对象,而且还会将自身添加到父视图中。这是由UIViewController处理的。

self.view = anotherView;



你的setCurrentView应该差不多是这样的,

- (void) replaceSubview:(UIView *)newView {
  CGRect frame = mySubview.frame;

  [mySubview removeFromSuperview];
  self.mySubview = newView;

  [self.view addSubview:newView];
  newView.frame = frame;
}



于 2010-02-05T16:50:27.823 回答
0

作为对@beefon 所说的话的回应。这有点像预期的那样,但背景颜色是透明的。它也没有响应......按钮没有被按下等......

- (void)setCurrentView:(UIView *)newView {
    /*      1. save current view.frame: CGRect mySubViewFrame = [mySubView frame]; 
            2. remove and put new subview - I have wrote how to do it 
            3. set new frame for new view: [mySubView setFrame:mySubViewFrame];      */ 
    CGRect currentViewFrame = [currentView frame];
    [currentView removeFromSuperview];
    [currentView autorelease];
    currentView = [newView retain];
    [self.view addSubview:currentView];
    [currentView setFrame:currentViewFrame]; 
}
于 2010-02-05T15:05:30.437 回答
-1

您的实例变量必须是一个属性才能使用点。语法,使用:

@Property (nonatomic, retain) IBOutlet UIView* subview;

在标题中,并使用:

@synthesize subview;

在主文件中。

为了使用点设置 UIView。您需要使其成为属性的语法。这也允许您subview在类之外设置 的属性。

于 2010-02-04T14:01:47.443 回答