我正在尝试根据UISlider的值移动UIView中绘制的点。下面的代码是UIView(子视图?),在UIViewController上有一个自定义类(WindowView)。
WindowView.h
#import <UIKit/UIKit.h>
@interface WindowView : UIView
- (IBAction)sliderValue:(UISlider *)sender;
@property (weak, nonatomic) IBOutlet UILabel *windowLabel;
@end
WindowView.m
#import "WindowView.h"
@interface WindowView ()
{
float myVal; // I thought my solution was using an iVar but I think I am wrong
}
@end
@implementation WindowView
@synthesize windowLabel;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)sliderValue:(UISlider *)sender
{
myVal = sender.value;
windowLabel.text = [NSString stringWithFormat:@"%f", myVal];
}
- (void)drawRect:(CGRect)rect
{
// I need to get the current value of the slider in drawRect: and update the position of the circle as the slider moves
UIBezierPath *circle = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(myVal, myVal, 10, 10)];
[circle fill];
}
@end
答案 0 :(得分:1)
好的,您需要将滑块值存储在实例变量中,然后强制视图重绘。
WindowView.h:
#import <UIKit/UIKit.h>
@interface WindowView : UIView
{
float _sliderValue; // Current value of the slider
}
// This should be called sliderValueChanged
- (IBAction)sliderValue:(UISlider *)sender;
@property (weak, nonatomic) IBOutlet UILabel *windowLabel;
@end
WindowView.m(仅限修改后的方法):
// This should be called sliderValueChanged
- (void)sliderValue:(UISlider *)sender
{
_sliderValue = sender.value;
[self setNeedsDisplay]; // Force redraw
}
- (void)drawRect:(CGRect)rect
{
UIBezierPath *circle = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(_sliderValue, _sliderValue, 10, 10)];
[circle fill];
}
您可能希望将_sliderValue
初始化为视图的init方法中有用的东西。
同样_sliderValue
可能不是您要选择的名称;也许像_circleOffset
或类似的东西。