【发布时间】:2010-12-11 13:11:07
【问题描述】:
我是 Objective-c 的新手,所以请耐心等待。这看起来很简单,但我一定做错了什么。在 IB 中,我创建了一个对象,将其命名为 AppController,然后添加了一个名为 makeView 的操作和两个 IBOutlets,btnMakeView 和 mainWin,然后正确连接所有内容并从中编写类文件。
在 AppController.h 我有这个代码:
#import <Cocoa/Cocoa.h>
@interface AppController : NSObject {
IBOutlet NSWindow * mainWin;
IBOutlet id btnMakeView;
}
- (IBAction)makeView:(id)sender;
@end
在 AppController.m 中这段代码:
#import "AppController.h"
#import "ViewController.h"
@implementation AppController
- (IBAction)makeView:(id)sender {
//declare a new instance of viewcontroller, which inherits fromNSView, were going to allocate it with
//a frame and set the bounds of that frame using NSMakeRect and the floats we plug in.
ViewController* testbox = [[ViewController alloc]initWithFrame:NSMakeRect(10.0, 10.0, 100.0, 20.0)];
//this tells the window to add our subview testbox to it's contentview
[[mainWin contentView]addSubview:testbox];
}
-(BOOL)isFlipped {
return YES;
}
@end
在 ViewController.h 我有这个代码:
#import <Cocoa/Cocoa.h>
@interface ViewController : NSView {
}
@end
最后在 ViewController.m 我有这个代码:
#import "ViewController.h"
@implementation ViewController
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
}
return self;
}
- (void)drawRect:(NSRect)rect {
// Drawing code here.
//sets the background color of the view object
[[NSColor redColor]set];
//fills the bounds of the view object with the background color
NSRectFill([self bounds]);
}
@end
它编译得很好,没有错误但没有得到一个对象,我假设它是一个矩形,从 x,y 10/10 开始,为 100x20。我做错了什么?
【问题讨论】:
-
只是补充一点,我已经记录了 ViewController 的 initWithFrame 方法,以确保我到达那里并且我到达了。
-
请注意,您可以通过缩进四个空格将行格式化为代码。编辑器工具栏中的“101\n010”按钮为您完成此操作。单击编辑器工具栏中的橙色问号以获取有关格式设置的更多信息和提示。您现在可以编辑帖子并修正格式。
-
outis,谢谢,每次我使用 101\n010 按钮输入代码时,它的格式都会很糟糕,正如你所知道的那样。不知道为什么。不知道缩进,但以后会使用它,以及接受答案功能,也不知道。
-
代码按钮的行为会有所不同,具体取决于是否有任何选定的文本,以及所有行是否缩进至少 4 个空格。它充当切换开关,在代码(通过缩进)和非代码(通过取消缩进)之间切换。制表符有问题。我建议用四个空格替换源代码中的所有选项卡(您可以使用搜索和替换,或谷歌了解如何配置 XCode 以使用空格)。
标签: objective-c xcode view