我有一个名为NSView的OneView子类,其代码如下:
#import "OneView.h"
@interface OneView ()
@property (strong, nonatomic) NSGradient *gradient;
@end
@implementation OneView
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
NSColor *top = [NSColor colorWithCalibratedRed:1.0 green:0.0 blue:0.0 alpha:1.0];
NSColor *btm = [NSColor colorWithCalibratedRed:0.0 green:0.0 blue:0.0 alpha:1.0];
self.gradient = [[NSGradient alloc] initWithStartingColor:top endingColor:btm];
[self.gradient drawInRect:self.bounds angle:270];
}
# pragma mark - Public
- (void)changeGradient {
self.gradient = nil;
NSColor *top = [NSColor colorWithCalibratedRed:0.0 green:1.0 blue:0.0 alpha:1.0];
NSColor *btm = [NSColor colorWithCalibratedRed:0.0 green:0.0 blue:0.0 alpha:1.0];
self.gradient = [[NSGradient alloc] initWithStartingColor:top endingColor:btm];
[self.gradient drawInRect:self.bounds angle:270];
[self setNeedsDisplay:YES];
}
@end在我的AppDelegate (或者可能是任何其他类)中,我试图通过调用OneView类的changeGradient方法来改变渐变的颜色:
#import "AppDelegate.h"
#import "OneView.h"
@interface AppDelegate ()
@property (weak, nonatomic) IBOutlet OneView *oneView;
@end
@implementation AppDelegate
- (IBAction)changeGradient:(id)sender {
[self.oneView changeGradient];
}
@end当第一次加载视图时,梯度将按预期进行初始化,但我无法更改IBAction方法中的梯度。我已经使用层支持视图实现了这一点,但是我正在试图找到一种不依赖于层来实现向后兼容性的方法。
对于为什么IBAction不改变梯度有什么想法吗?

发布于 2014-07-22 04:25:07
问题是self.gradient = [[NSGradient alloc] initWithStartingColor:top endingColor:btm];在drawRect:函数中。将其更改为if (!self.gradient) { self.gradient = [[NSGradient alloc] initWithStartingColor:top endingColor:btm]; }将修复此问题。顺便说一句,您不应该在drawRect:方法中创建渐变。这会伤到演出的。在这种情况下,应该将初始化放在awakeFromNib方法中。
发布于 2014-07-22 04:25:49
您的drawRect:方法总是会在其中绘制相同的东西。您不应该尝试在drawRect之外绘制:如果渐变为零,则实际上只需要在viewWillDraw:中设置梯度。
您可能应该重新设计,使渐变的颜色也是视图的属性。然后使用KVO通过调用setNeedsDisplay:是的来观察和响应任何颜色的变化
如果你需要更多,我可以在回到电脑后发帖。
https://stackoverflow.com/questions/24878018
复制相似问题