使用Button更改图像位置

时间:2013-10-18 23:58:46

标签: ios button uiview position

我想用按钮改变三个不同位置的图像位置...... 使用我的代码,图像只能移动一个位置......

ViewController.h

@property (weak, nonatomic) IBOutlet UIImageView *Switch3Way;

- (IBAction)Switch3WayPressed:(id)sender;

ViewController.m

- (void)Switch3WayPressed:(id)sender {
CGRect frame = Switch3Way.frame;
frame.origin.x = 323;
frame.origin.y = 262;
Switch3Way.frame = frame;

}

2 个答案:

答案 0 :(得分:1)

您是否可以指定需要将按钮移动到三个不同位置的要求?无论如何,我希望你能根据一些逻辑进行更改 - 所以在头文件中定义三个枚举,例如如下所示:

typedef enum {
buttonState1,
buttonState2,
buttonState3
} buttonState;

然后,根据您的业务逻辑要求,将这些枚举变量设置在代码中的适当位置,例如如下所示:

-(void)setButtonState{

buttonState = buttonState1;

}

现在,在按钮触摸内部处理程序例程中,使用switch语句设置适当的帧,例如如下所示:

- (void)Switch3WayPressed:(id)sender {
    if (![sender isKindOfClass:[Switch3Way class]])
    return;
 switch (buttonState)

 {
 case buttonState1:
      {
      CGRect frame = Switch3Way.frame;
      frame.origin.x = 323;
      frame.origin.y = 262;
      Switch3Way.frame = frame;
      break;
   }
 case buttonState2:
      //some other rect origin based on your logic
      break;
 case buttonState3:
      //some other rect origin based on your logic
      break;
 default:
      break;

 }

答案 1 :(得分:1)

以下代码假定您要为Switch3Way UIImageView IBOutlet属性设置动画。此代码段将您的UIImageView移动到三个不同的位置,并在最后位置停止动画。

#import <QuartzCore/QuartzCore.h>    

-(IBAction)move:(id)sender
{
    CGPoint firstPosition = CGPointMake(someXvalue, someYvalue);
    CGPoint secondPosition = CGPointMake(someXvalue, someYvalue);
    CGPoint thirdPosition  = CGPointMake(someXvalue, someYvalue);

    CABasicAnimation *posOne = [CABasicAnimation animationWithKeyPath:@"position"];
    posOne.fromValue = [NSValue valueWithCGPoint:_Switch3Way.layer.position];
    posOne.toValue   = [NSValue valueWithCGPoint:firstPosition];
    posOne.beginTime = 0;
    posOne.duration  = 1;

    CABasicAnimation *posTwo = [CABasicAnimation animationWithKeyPath:@"position"];
    posTwo.fromValue = [NSValue valueWithCGPoint:firstPosition];
    posTwo.toValue   = [NSValue valueWithCGPoint:secondPosition];
    posTwo.beginTime = 1;
    posTwo.duration  = 1;

    CABasicAnimation *posThree = [CABasicAnimation animationWithKeyPath:@"position"];
    posThree.fromValue = [NSValue valueWithCGPoint:secondPosition];
    posThree.toValue   = [NSValue valueWithCGPoint:thirdPosition];
    posThree.beginTime = 2;
    posThree.duration  = 1;

    CAAnimationGroup *anims = [CAAnimationGroup animation];
    anims.animations = [NSArray arrayWithObjects:posOne, posTwo, posThree, nil];
    anims.duration = 3;
    anims.fillMode = kCAFillModeForwards;
    anims.removedOnCompletion = NO;

    [_Switch3Way.layer addAnimation:anims forKey:nil];

    _Switch3Way.layer.position = thirdPosition;
}

Invasivecode有一系列非常好的关于创建动画的教程,就像你所指的那样http://weblog.invasivecode.com/post/4448661320/core-animation-part-iii-basic-animations你最终会想要使用CAKeyframeAnimation对象来创建这些类型的动画,但是理解CABasicAnimations是开始创建动画的好方法。使用CoreAnimation。