2013-05-22 5 views
1

Я пытаюсь переместить точку, нарисованную в UIView, на основе значения UISlider. Код ниже для UIView (subview?) С пользовательским классом (WindowView) на UIViewController.Получить текущее значение UISlider в drawRect: метод

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 

ответ

1

OK, вам необходимо сохранить значение ползунка в переменной экземпляра, а затем заставить вид перерисовывать.

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 к чему-то полезное в методе инициализации представления.

Также _sliderValue, вероятно, не имя, которое вы хотите выбрать; возможно, что-то вроде _circleOffset или некоторые такие.

+0

Sweet! Я знал, что это просто. Спасибо, миллиард! –

Смежные вопросы