简体   繁体   English

在按住UIButton时移除阴影

[英]Removing the shadow on a UIButton while it's being held

I have a UIButton which highlighted state involves removing the shadow. 我有一个UIButton ,突出显示状态涉及删除阴影。 What I tried doing is putting a UILongPressGestureRecognizer onto the button: 我尝试做的是将UILongPressGestureRecognizer放在按钮上:

let gesture = UILongPressGestureRecognizer(target: self, action: #selector(self.removeShadow))
gesture.numberOfTapsRequired = 1
gesture.numberOfTouchesRequired = 1
gesture.delaysTouchesBegan = false
gesture.delaysTouchesEnded = false
gesture.minimumPressDuration = 0.01
self.addGestureRecognizer(gesture)

Then in my action, I'm using the states to hide and show the shadow: 然后在动作中,我使用状态来隐藏和显示阴影:

 @objc func removeShadow(gesture: UILongPressGestureRecognizer) {
    if gesture.state == .recognized {
        UIView.animate(withDuration: 0.1, animations: {
            self.layer.shadowOpacity = 0
        })
    } else if gesture.state == .ended {
        UIView.animate(withDuration: 0.1, animations: {
            self.layer.shadowOpacity = 0.15
        })
    }
}

However, this doesn't seem to trigger anything. 但是,这似乎没有触发任何东西。 The shadow keeps living under the button. 阴影一直存在于按钮下方。 Am I missing something here? 我在这里想念什么吗?

Thanks. 谢谢。

Your gesture recognizer is being overridden by the selector of the button. 您的手势识别器已被按钮的选择器覆盖。 It'd be better in your scenario to override the button and hide its shadow when it's selected. 在您的方案中,最好覆盖按钮并在选择按钮时隐藏其阴影。

class ShadowButton: UIButton {
    override var isHighlighted: Bool {
        didSet {
            UIView.animate(withDuration: 0.1) {
                self.layer.shadowOpacity = self.isHighlighted ? 0 : 0.15
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM