【问题标题】:Working UIButton animations in Swift在 Swift 中使用 UIButton 动画
【发布时间】:2015-11-11 20:26:26
【问题描述】:

我一直试图让这段代码工作,但我似乎无法让我的 UIButton 通过图像进行动画处理。

@IBOutlet weak var screenButton: UIButton!;

func animation(){
        var animationButton : UIButton!; 
        var imageList = [UIImage]();
        var image1:UIImage = UIImage(named:"3fingers-o-l-animation1.png")!;
        var image2:UIImage = UIImage(named:"4fingers-o-l-animation1.png")!;

        animationButtonscreenButton = screenButton;
        imageList = [image1, image2];

        animationButton!.imageView!.animationImages = imageList;
        animationButton!.imageView!.animationDuration = 1.0;
        animationButton!.imageView!.startAnimating();
    }

编写此代码后,我将一条线从 screenButton 拖到我想要通过 Storyboard 中的图像制作动画的按钮。 我究竟做错了什么?

【问题讨论】:

  • UIButton 未初始化...
  • 这就是为什么你应该在适当的时候使用?!。不要?所有代码,因为它会隐藏错误。如果应该存在某些东西,请使用强制解包!。或者在这种情况下只是一个非可选变量。你会很早就看到这个问题。
  • i) 初始化 UIButton ii) 设置它的框架 iii) addSubview 在你的视图上
  • 我已经尝试了您的建议,但仍然无法正常工作。我已经用我所做的事情编辑了我的问题。

标签: ios swift animation uibutton


【解决方案1】:

你需要做的是不要在函数animation中重新初始化UIButton;所以,注释掉这一行:

//var animationButton : UIButton!

除了只有一个IBOutlet,我们还需要一个IBAction 到你的函数animation。通过控制将“线”拖动到功能块(检查IBAction,而不是IBOutlet),执行与按钮相同的操作。

当你还在故事板中的时候做一个小演练:


  • 您所拥有的只有一个名为:animationButton 的按钮,它是一个 IBOutlet,通过控制拖动一条“线”从您的故事板到您的代码。

  • 对于您的 animation 函数: 按住 Control 并从情节提要中将按钮从“线”拖到 animation 函数的块中。

  • 在情节提要中为您的按钮设置初始图像,如下所述。

另外,我们需要在storyboard中设置一个初始图片;否则,按钮的图像属性为nil

请通过单击右侧的“属性检查器”在情节提要中执行此操作,然后在显示“图像”的位置设置图像。作为测试,我将其设置为“1.jpg”。

因此,您的代码应如下所示:

@IBOutlet weak var animationButton: UIButton!
@IBAction func animation()
{
    print("button touched")
    //var animationButton : UIButton!
    var imageList = [UIImage]()
    var image1:UIImage = UIImage(named:"1.jpg")!
    var image2:UIImage = UIImage(named:"2.jpg")!

    //animationButtonscreenButton = screenButton;
    imageList = [image1, image2];

    animationButton!.imageView!.animationImages = imageList
    animationButton!.imageView!.animationDuration = 1.0
    animationButton!.imageView!.startAnimating()
}

刚刚进行了快速测试;它获取触摸事件,并且按钮上的图像动画。希望这会有所帮助。

【讨论】:

  • 谢谢。在阅读您的答案时,我发现我的代码有什么问题。我的按钮的图像属性为零。在该字段中放置图像解决了我的问题,我的屏幕现在像疯了一样动画!
猜你喜欢
  • 1970-01-01
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-28
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
相关资源
最近更新 更多