Home Ask Login Register

Developers Planet

Your answer is one click away!

hullabal00 February 2016

Redrawing a UIView using NSTimer not working as expected

I subclassed UIView in order to draw a line that changes position every second. I am using NSTimer to call setNeedsDisplay in order to update the view but the results are not correct. It is drawing old and new lines. Here is my LineView.h/m code:


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


#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];

In my ViewController.m file, in viewDidLoad, I init lineView and start the timer:

- (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;

I want to do this all programmatically and not use storyboards or xibs. If I subclass the view in storyboard and create an outlet to it, then the view is updated correctly but I want to avoid touching the storyboard.


Muhammad Zohaib Ehsan February 2016

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

try this. I have run your project with this it doing good.

Post Status

Asked in February 2016
Viewed 1,309 times
Voted 4
Answered 1 times


Leave an answer

Quote of the day: live life