【问题标题】:Getting Subview from another Subview从另一个子视图获取子视图
【发布时间】:2012-04-18 07:59:50
【问题描述】:

我的主窗口的内容视图设置如下:

 newContentView = [[CutoutView alloc]initWithFrame:window.frame];
     [window setContentView:newContentView];
     [newContentView release];

CutoutView 是我的子类的名称。现在我想给它添加一个子视图,所以我做了以下,

filterView = [[FilterView alloc]initWithFrame:NSMakeRect(100, 100, 500, 500)]; 
    [newContentView addSubview:filterView];
    [filterView release];

除了现在我想从我的 filterView 子类中调用方法并且我想像这样得到它但它不会工作之外,一切都很好。

FilterView *filter = [[NSApp delegate] contentView]; 

我在文档中读到,通过使用 contentView 它只会“返回窗口层次结构中可访问的最高 NSView 对象”所以我尝试将以下内容添加到 addSubview

[newContentView addSubview:filterView positioned:NSWindowAbove relativeTo:nil];

但这对我需要做什么没有任何想法?谢谢!

【问题讨论】:

  • 我通常只是添加一个属性来跟踪我以后想要访问的视图。
  • 好的,我做了@property (nonatomic, strong) FilterView *filterView;,但我如何访问另一个类中的该属性以获取其方法?
  • 假设它是您的应用程序委托的一部分,您只需获取应用程序委托的句柄,如 MyAppDelegateClass *appDelegate = [[UIApplication sharedApplication] delegate];,然后从中获取属性。
  • 好的,所以对于mac来说它是MyAppDelegateClass *appDelegate = [[NSApp sharedApplication] delegate];,然后我会做[appDelegate filterView],但是要获得方法,我应该在最后一段代码中添加什么?感谢您的帮助!

标签: objective-c xcode cocoa


【解决方案1】:

内容视图实际上是您的 CutoutView 类,因此您应该使用:

FilterView *filterView = [[[[[NSApp delegate] window] contentView] subviews] objectAtIndex:0];

但是两种更简洁的方法是:

1) 使用 IBOutlets 跟踪您的视图并通过 IB 分配它们。 2)使用标签:

filterView.tag = 101;

然后使用:

FilterView* filterView = [[[NSApp delegate] contentView] viewWithTag:101];

【讨论】:

  • 当我尝试使用标签并将其设置为 filterView.tag = 101; 时的一个快速问题,它给了我消息,No setter method 'setTag' for assignment to property 那么我需要添加什么?谢谢!
  • 我不得不道歉 - 似乎 NSViews 没有标签。 iOS 上的 UIViews 确实有它们。 Mac 程序员可以确认吗?
  • 文档说Subclasses can override this method to provide individual tags, possibly adding storage and a setTag: method (which NSView doesn’t define).
【解决方案2】:

ContentView 是您的窗口而不是应用程序委托的方法,因此如果您的应用程序委托中有一个 IBOutlet 为“窗口”的窗口,那么您需要使用:FilterView *filter = [[[NSApp delegate] window]内容视图];

【讨论】:

  • 好的,我添加了 window] contentView] 但是现在当我尝试从我的 FilterView 获取方法时,它崩溃并显示-[CutoutView myMethod]: unrecognized selector sent to instance 0x1050415a0,这意味着它只访问名为“CutoutView”的主视图子类,而不是我想要的 sublcas 是名为“filterView”的子视图
猜你喜欢
  • 2016-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 2018-04-07
  • 1970-01-01
相关资源
最近更新 更多