使用 NSTimer 重绘 UIView 未按预期工作

Redrawing a UIView using NSTimer not working as expected

我将 UIView 子类化,以便绘制一条每秒改变位置的线。我正在使用 NSTimer 调用 setNeedsDisplay 以更新视图,但结果不正确。它正在绘制旧线和新线。这是我的 LineView。h/m 代码:

LineView.h:

@interface LineView : UIView
@property(nonatomic, assign) int length;
@end

LineView.m:

#import "LineView.h"
@implementation LineView
- (void)setLength:(int)length {
    _length = length;
    [self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {    
    UIBezierPath *line = [UIBezierPath bezierPath];
    [line moveToPoint:CGPointMake(10, 10)];
    [line addLineToPoint:CGPointMake(100, 100+_length)];
    line.lineWidth = 10;
    [[UIColor blueColor] setStroke];
    [line stroke];
}
@end

在我的 ViewController.m 文件中,在 viewDidLoad 中,我初始化了 lineView 并启动了计时器:

- (void)viewDidLoad {
    [super viewDidLoad];
    _length = 100;

    _lineView = [[LineView alloc]initWithFrame:self.view.bounds];
    _lineView.length = _length;
    [self.view addSubview:_lineView];

    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:true];
}

- (void)updateTime:(NSTimer*)timer {
    _length += 20;
    self.lineView.length = _length;
}

我想以编程方式完成这一切,而不是使用故事板或 xib。如果我在故事板中子类化视图并为它创建一个出口,那么视图会正确更新,但我想避免接触故事板。

_lineView.opaque = NO;
_lineView.backgroundColor = [UIColor blackColor];

试试这个。我有 运行 你的项目,它做得很好。