【发布时间】:2012-04-07 01:58:55
【问题描述】:
我正在尝试在自定义视图 (rectView) 中创建一个 CGRect,它会在您移动滑块时上下移动。
我的滑块的 IBAction 调用了以下方法:(这很好)
- (void)moveRectUpOrDown:(int)y
{
self.verticalPositionOfRect += y;
[self setNeedsDisplay];
}
我的drawRect方法:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat size = 100;
self.rect = CGRectMake((self.bounds.size.width / 2) - (size / 2),
self.verticalPositionOfRect - (size / 2),
size,
size);
CGContextAddRect(context, self.rect);
CGContextFillPath(context);
}
我的自定义视图的 initWithFrame 使用 setNeedsDisplay 调用 drawRect 方法,但由于某种原因 moveRectUpOrDown 不会调用 drawRect。
任何想法我做错了什么?
为清楚起见,整个实现如下:
//ViewController.h
#import <UIKit/UIKit.h>
#import "rectView.h"
@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet rectView *rectView;
- (IBAction)sliderChanged:(id)sender;
@end
//ViewController.m
#import "ViewController.h"
@implementation ViewController
@synthesize rectView;
- (void)viewDidLoad
{
[super viewDidLoad];
self.rectView = [[rectView alloc] initWithFrame:self.rectView.frame];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)sliderChanged:(id)sender
{
UISlider *slider = sender;
CGFloat sliderValue = slider.value;
[self.rectView moveRectUpOrDown:sliderValue];
}
@end
//rectView.h
#import <UIKit/UIKit.h>
@interface rectView : UIView
- (void)moveRectUpOrDown:(int)y;
@end
//rectView.m
#import "rectView.h"
@interface rectView ()
@property CGRect rect;
@property int verticalPositionOfRect;
@end
@implementation rectView
@synthesize rect, verticalPositionOfRect;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.verticalPositionOfRect = (self.bounds.size.height / 2);
[self setNeedsDisplay];
}
return self;
}
- (void)moveRectUpOrDown:(int)y
{
self.verticalPositionOfRect += y;
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat size = 100.0;
self.rect = CGRectMake((self.bounds.size.width / 2) - (size / 2),
self.verticalPositionOfRect - (size / 2),
size,
size);
CGContextAddRect(context, self.rect);
CGContextFillPath(context);
}
@end
感谢您的帮助:)
【问题讨论】:
-
我想只添加一个
CALayer并对其进行上下动画处理会比一直重绘更有效 -
还没有调查过,但我现在会调查一下。我基本上这样做是为了让我了解 Quartz 的基础知识
-
所以您已经确认
-drawRect:没有被调用?还是叫不画? -
它根本没有被调用,我在里面放了一个 NSLog 来测试。 drawRect 仅在视图 initWithFrame 中被调用一次,但在更改滑块的值时不会被调用(从滑块的 IBAction 调用 setNeedsDisplay is)但它不会调用 drawRect?
-
self是实际的视图吗?或父母。也许试试[self.myView setNeedsDisplay]
标签: iphone ios cocoa quartz-graphics