【发布时间】:2014-05-26 10:08:38
【问题描述】:
我正在尝试以编程方式更新视图。因此我有一个控制器和一个视图。控制器应在按下按钮时更新视图。但是,尽管方法被调用,但视图并没有明显更新。
我发现NSView 的对象 ID 不同于控制器保留的对象 ID。 (这是正确的术语吗?)
这是代码:
// myView.h
#import <Cocoa/Cocoa.h>
@interface myView : NSView
{
int numberToDisplay;
}
-(void)seedNumber;
-(int)numberToDisplay;
@end
--------------------------------------------------------
// myView.m
#import "myView.h"
@implementation myView
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSLog(@"View loaded\n%@",self);
numberToDisplay = 0;
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect
{
[super drawRect:dirtyRect];
NSLog(@"view is drawing");
//Draw
NSRect textRect = NSMakeRect(5, 5, 100, 100);
NSMutableParagraphStyle* textStyle = NSMutableParagraphStyle.defaultParagraphStyle.mutableCopy;
textStyle.alignment = NSCenterTextAlignment;
NSDictionary* textFontAttributes = @{NSFontAttributeName: [NSFont fontWithName: @"Helvetica" size: 50], NSForegroundColorAttributeName: NSColor.blackColor, NSParagraphStyleAttributeName: textStyle};
[[NSString stringWithFormat:@"%d",numberToDisplay] drawInRect: NSOffsetRect(textRect, 0, 1) withAttributes: textFontAttributes];
}
-(void)seedNumber;
{
numberToDisplay++;
NSLog(@"view:%d",numberToDisplay);
}
-(int)numberToDisplay
{
return numberToDisplay;
}
@end
--------------------------------------------------------
// controller.h
#import <Foundation/Foundation.h>
@class myView;
@interface controller : NSObject
{
myView *view;
}
-(IBAction)buttonPressed:(id)sender;
@end
--------------------------------------------------------
// controller.m
#import "controller.h"
#import "myView.h"
@implementation controller
-(void)awakeFromNib
{
view = [[myView alloc]init];
NSLog(@"controller loaded\n%@",view);
}
-(IBAction)buttonPressed:(id)sender
{
[view seedNumber];
NSLog(@"controller: %d",[view numberToDisplay]);
[view setNeedsDisplay:YES];
}
@end
--------------------------------------------------------
这就是命令行返回的内容(按下按钮时):
2014-05-26 11:58:20.036 graphikTest[1230:303] View loaded
<myView: 0x60000012e7e0>
2014-05-26 11:58:20.049 graphikTest[1230:303] View loaded
<myView: 0x60800012f140>
2014-05-26 11:58:20.049 graphikTest[1230:303] controller loaded
<myView: 0x60800012f140>
2014-05-26 11:58:20.087 graphikTest[1230:303] view is drawing
2014-05-26 11:58:22.083 graphikTest[1230:303] view:1
2014-05-26 11:58:22.083 graphikTest[1230:303] controller: 1
2014-05-26 11:58:22.982 graphikTest[1230:303] view:2
2014-05-26 11:58:22.983 graphikTest[1230:303] controller: 2
2014-05-26 11:58:23.432 graphikTest[1230:303] view:3
2014-05-26 11:58:23.433 graphikTest[1230:303] controller: 3
2014-05-26 11:58:23.635 graphikTest[1230:303] view:4
2014-05-26 11:58:23.636 graphikTest[1230:303] controller: 4
2014-05-26 11:58:23.849 graphikTest[1230:303] view:5
2014-05-26 11:58:23.850 graphikTest[1230:303] controller: 5
... 所以它应该真的有效——我不知道为什么它不重绘。 有人有想法吗?
【问题讨论】:
-
请编辑your existing question而不是转发。
标签: objective-c cocoa nsview