如何在不移动按钮的情况下增加UIButton图像的高度

时间:2015-05-22 19:44:37

标签: swift uiview uibutton

我在故事板中添加了UIButton,然后将我的图片添加到按钮中。我要做的是当你点击按钮时,高度稍微增加,然后按钮的高度减少了大约四分之一。

@IBAction func StopsClick(sender: UIView) {
    //Get the y coordinates of Image
    let origin = sender.bounds.origin.y

    //This decreases the height of Image but the image moved. I want the image to remain stationary and only the top of the image to increase in height.
    UIView.animateWithDuration(0.5) {
        sender.bounds = CGRectMake(0, origin, sender.bounds.width, sender.bounds.height * 1.2)
    }

    UIView.animateWithDuration(1.0) {
        sender.bounds = CGRectMake(0, orgin, sender.bounds.width, sender.bounds.height * 0.4)
    }
}

1 个答案:

答案 0 :(得分:0)

您应该能够在使用变换后获得效果。

我会做以下事情:

从身份转换开始。 将变换的原点向下移动到图像的底部。 根据需要增加变换的比例。 将变换的原点移回图像的中心

将该变换应用于动画中的按钮。然后将其动画回身份变换。

如果你没有移动变换并只进行缩放,它将从中心向所有方向增长。 (如果只增加比例,则只上下。)

编辑:

代码可能如下所示:

let halfHeight = button.bounds.height / 2

//Make the center of the grow animation be the bottom center of the button
var transform = CGAffineTransformMakeTranslation(0, -halfHeight)

//Animate the button to 120% of it's normal height.
tranform = CGAffineTransformScale( transform, 1.0, 1.2)
tranform = CGAffineTransformTranslate( transform, 0, halfHeight)
UIView.animateWithDuration(0.5)
{
  button.transform = transform
}

上面的代码将按钮设置为120%的高度,然后将其保留在那里。

您可以使用animateWithDuration的较长变体之一来获取使动画自动反转的选项。我把它作为练习留给你。

编辑#2:

我敲了一些代码来做一个三步动画:

func animateButton(step: Int)
{
  let localStep = step - 1

  let halfHeight = aButton.bounds.height / 2

  var transform: CGAffineTransform
  switch step
  {
  case 2:
    //Make the center of the grow animation be the bottom center of the button
    transform = CGAffineTransformMakeTranslation(0, -halfHeight)

    //Animate the button to 120% of it's normal height.
    transform = CGAffineTransformScale( transform, 1.0, 1.2)
    transform = CGAffineTransformTranslate( transform, 0, halfHeight)
    UIView.animateWithDuration(0.5, animations:
      {
        aButton.transform = transform
      },
      completion:
      {
        (finshed) in
        animateButton(step)
    })
  case 1:
    //In the second step, shrink the height down to .25 of normal
    transform = CGAffineTransformMakeTranslation(0, -halfHeight)

    //Animate the button to 120% of it's normal height.
    transform = CGAffineTransformScale( transform, 1.0, 0.25)
    transform = CGAffineTransformTranslate( transform, 0, halfHeight)
    UIView.animateWithDuration(0.5, animations:
      {
        aButton.transform = transform
      },
      completion:
      {
        (finshed) in
        animateButton(step)
    })
  case 0:
    //in the final step, animate the button back to full height.
    UIView.animateWithDuration(0.5)
      {
        aButton.transform = CGAffineTransformIdentity
      }
  default:
    break
  }
}

您可以使用

调用它
animateButton(3)

使用枚举作为步骤编号会更简洁,它可以使用一些范围检查来确保输入值为3,2或1,但是你明白了......