iOS:如何移动球

时间:2014-04-28 16:38:49

标签: ios uiview

您好我如何在iOS上创建移动球。

  • 程序启动时,我会在屏幕左侧显示球。随后,每次单击UIButton时,如何在同一x轴上向右移动球。

  • 我设法显示了球但是在按下UIButton时如何更新和重绘其位置?目前,每当我按下UIButton时,它会创建一个新球并且不会清除旧球。

  • 我理解它,因为我重新创建了一个新的球实例。那么我该如何解决这个问题呢?


这是我的代码......

ballView.m

@implementation BallView

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setBackgroundColor:[UIColor clearColor]];
    }

    return self;
}

-(void)drawRect:(CGRect)dirtyRect
{
    NSLog(@"in drawRect");

    // Get the graphics context and clear it
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // Draw a solid ball
    CGContextSetRGBFillColor(ctx, 0, 0, 0, 1);
    CGContextFillEllipseInRect(ctx, dirtyRect);

    [self setNeedsDisplay];
}

-(BOOL)canBecomeFirstResponder
{
    return YES;
}

MoveBallController.m

-(void)moveBall
{

    CGRect viewFrame = CGRectMake(0, 0, 30, 30);
    BallView *ball = [[BallView alloc] initWithFrame:viewFrame];
    [[self dotView] addSubview:ball];

}

1 个答案:

答案 0 :(得分:3)

创建一个BallView实例并将其存储在实例变量中。然后当单击按钮时,您只需更新球的框架:

- (void)viewDidLoad {
    [super viewDidLoad];

    CGRect viewFrame = CGRectMake(0, 0, 30, 30);
    _ball = [[BallView alloc] initWithFrame:viewFrame];
    [[self dotView] addSubview:_ball];
}

- (void)moveBall {
    CGRect frame = _ball.frame;
    frame.origin.x += 5; // use some appropriate increment
    _ball.frame = frame;
}

其中_ball是您的新实例变量。

相关问题