【问题标题】:Get the current value of UISlider in drawRect: method在drawRect:方法中获取UISlider的当前值
【发布时间】:2013-05-22 00:46:02
【问题描述】:

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

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

【问题讨论】:

    标签: ios objective-c uiview uislider uibezierpath


    【解决方案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 之类的。

    【讨论】:

    • 甜蜜!我知道这很简单。谢谢十亿!
    猜你喜欢
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    相关资源
    最近更新 更多