NSView的子类不会刷新/重绘,但会调用-drawRect



我有一个简单的测试应用程序,我有问题。UI是两个滑块(x &y)和一个自定义视图,我在上面画一个红点。现在,圆点将显示在初始位置,但不会随着滑块移动。使用NSLog,我可以知道当我移动滑块时,drawRect正在被调用,x和y数据是当前的。NSView的子类:

#import <Cocoa/Cocoa.h>

@interface BallView : NSView {
    NSRect rect;
    NSBezierPath *bp2;
}
@property (readwrite) NSRect rect;
@end
#import "BallView.h"

@implementation BallView
@synthesize rect;
- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    rect = NSMakeRect(50, 10, 10, 10);
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
    NSLog(@"draw rect: %f, %f", rect.origin.x, rect.origin.y);
    bp2 = [NSBezierPath bezierPath]; 
    [bp2 appendBezierPathWithOvalInRect: rect];
    NSColor *color2 = [NSColor redColor];
    [color2 set];
    [bp2 fill]; 
}

在应用程序委托中获取滑块值rect:

-(IBAction) setX:(id)sender{
x=[sender floatValue];
[ballView setRect: NSMakeRect(x, y, 10, 10)];
NSLog(@"set x");
}
-(IBAction) setY:(id)sender{
    y= [sender floatValue];
    [ballView setRect: NSMakeRect(x, y, 10, 10)];
    NSLog(@"set y");
}

不要告诉视图它需要重绘。把

[ballView setNeedsDisplay:YES];

到状态改变动作中。我通常会为此目的实现setter让它们从视图内部调用这个,而不是合成它。

最新更新