为不同的对象实现相同的功能

时间:2018-12-16 22:52:58

标签: swift

新手编码员,学习Swift。我希望该函数对两个UIButton都适用,并且不知道如何使它在第二个UIButton中实现。

private lazy var boostButton: UIButton = {
    let button = UIButton(type: .custom)

    button.frame = CGRect(x: 10, y: 10, width: 80, height: 80)
    button.setImage(UIImage(named: "simsek.png"), for: .normal)
    button.imageView?.contentMode = .scaleAspectFit
    button.contentHorizontalAlignment = .center
    button.contentVerticalAlignment = .center
    button.layer.cornerRadius = 0.5 * button.bounds.size.width
    button.layer.masksToBounds = true
    button.addTarget(self, action: #selector(touchDown), for: [.touchDown, .touchDragEnter])
    button.addTarget(self, action: #selector(touchUp), for: [.touchUpInside, .touchDragExit, .touchCancel])

    return button
}()

private lazy var informationButton: UIButton = {
    let button = UIButton(type: .custom)

    button.frame = CGRect(x: 120, y: 10, width: 35, height: 35)
    button.setImage(UIImage(named: "yenigozlukgri.png"), for: .normal)
    button.imageView?.contentMode = .scaleAspectFit
    button.contentHorizontalAlignment = .center
    button.contentVerticalAlignment = .center
    button.layer.cornerRadius = 0.5 * button.bounds.size.width
    button.layer.masksToBounds = true
    button.addTarget(self, action: #selector(touchDown), for: [.touchDown, .touchDragEnter])
    button.addTarget(self, action: #selector(touchUp), for: [.touchUpInside, .touchDragExit, .touchCancel])

    return button
}()

这些是我的按钮。我不使用情节提要,但我认为这对于解决方案不是必不可少的。

@objc func touchDown() {
    animator.stopAnimation(true)
    boostButton.backgroundColor = .red
    //highlightedColor
}

@objc func touchUp() {
    animator = UIViewPropertyAnimator(duration: 0.5, curve: .easeOut, animations: {
        self.boostButton.backgroundColor = .gray
    })
    animator.startAnimation()
}

我想做的是,当单击其中一个按钮时,它应该执行动画。如果我在函数中添加像 boostButton 这样的 informationButton ,即使单击一个按钮,它们两个都将执行动画。它应该只适用于被点击的那个。如何解决更多按钮的功能?

1 个答案:

答案 0 :(得分:0)

使用参数

 @objc func touchDown(_ sender:UIButton) {
    animator.stopAnimation(true)
    sender.backgroundColor = .red
    //highlightedColor
}

@objc func touchUp(_ sender:UIButton) {
    animator = UIViewPropertyAnimator(duration: 0.5, curve: .easeOut, animations: {
         sender.backgroundColor = .gray
    })
    animator.startAnimation()
}