【问题标题】:Accessing View from ViewController从 ViewController 访问视图
【发布时间】:2013-09-01 20:35:09
【问题描述】:

我在 StoryBoard 中创建了一个 ViewController 并将其与 GamePanelViewController 类链接。 此外,我将 ViewController 的视图与名为 GamePanel 的第二个类关联起来,该类扩展了 UIView。

如何访问由 StoryBoard 自动创建的视图,以执行我对 GamePanel 类实现的一些方法,该类通过身份检查器链接到视图?

GamePanel.h:

#import <UIKit/UIKit.h>
#import "Plattform.h"

@interface GamePanel : UIView

@property (strong, nonatomic) NSMutableArray *plattforms;

- (void)initGamePanel;
- (void)drawPlattforms:(CGContextRef)gc;

@end

GamePanel.m:

#import "GamePanel.h"

@implementation GamePanel

@synthesize plattforms;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

    }
    return self;
}

- (void)initGamePanel{
   self.backgroundColor = [UIColor redColor];

    self.plattforms = [NSMutableArray new];
    // Initialization code
    for(int i = 0;i<8;i++){
        for(int j = 0;j<6;j++){
            [self.plattforms addObject:[[Plattform alloc] initWithXCord:(14+j*37) andYCoord:(58+14+i*37)]];
            NSLog(@"Init");
        }
    }
}

【问题讨论】:

    标签: objective-c view uiviewcontroller


    【解决方案1】:

    如果您实际上已将 viewController 的 view 属性与您的自定义视图相关联,那么您只需在 viewController 中使用 self.view 即可访问它。

    如果您刚刚将 UIView 拖到情节提要中的 viewController 上(并且没有将其链接到 viewController 的 view 属性),您将需要为它创建一个 IBOutlet(从视图中控制拖动到您的界面,并给出它是一个名字),然后你可以用你给它的名字来引用它,例如self.myView.

    【讨论】:

    • 在连接检查器中,我可以看到视图出口实际上与名为“GamePanel”的视图链接。但是,如果我尝试从 ViewController 调用方法“initGamePanel”,则会收到以下错误消息:[self.view initGamePanel]; - 'UIView' 没有可见的@interface 声明选择器'initGamePanel'
    • 您需要将 self.view 投射到您的 GamePanel 类 - [(GamePanel *)self.view initGamePanel];
    • 现在我收到一条非常相似的错误消息:“GamePanel”没有可见的@interface 声明选择器“initGamePanel”:/ 我可以调用“initWithFrame”方法,但 initGamePanel 不起作用-.-
    • 您是否将initGamePanel 方法声明添加到GamePanel 的公共接口(.h 文件)?
    • 没问题,很高兴能帮上忙。
    猜你喜欢
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    相关资源
    最近更新 更多