1

我正在尝试根据 UISlider 的值移动在 UIView 中绘制的点。下面的代码适用于在 UIViewController 上具有自定义类 (WindowView) 的 UIView(子视图?)。

窗口视图.h

#import <UIKit/UIKit.h>

@interface WindowView : UIView

- (IBAction)sliderValue:(UISlider *)sender;

@property (weak, nonatomic) IBOutlet UILabel *windowLabel;


@end

窗口视图.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
4

1 回答 1

1

好的,您需要将滑块值存储在实例变量中,然后强制视图重绘。

窗口视图.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或类似的东西。

于 2013-05-22T00:56:27.280 回答