我正在尝试在自定义视图(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
谢谢您的帮助 :)